Factory Bot (Rails Testing)

Last updated

Factory Bot, originally known as Factory Girl, [1] is a software library for the Ruby programming language that provides factory methods to create test fixtures for automated software testing. The fixture objects can be created on the fly; they may be plain Ruby objects with a predefined state, ORM objects with existing database records or mock objects.

Contents

Factory Bot is often used in testing Ruby on Rails applications; where it replaces Rails' built-in fixture mechanism. Rails' default setup uses a pre-populated database as test fixtures, which are global for the complete test suite. Factory Bot, on the other hand, allows developers to define a different setup for each test and thus helps to avoid dependencies within the test suite. [2] [3]

Factories

Defining Factories

A factory is defined by a name and its set of attributes. The class of the test object is either determined through the name of the factory or set explicitly. [4]

FactoryBot.definedo# Determine class automaticallyfactory:userdoname{"Captain Minion"}superhero{false}end# Specify class explicitlyfactory:superhero,class:Userdoname{"Tony Stark"}superhero{true}endend

Features

Traits

Traits allow grouping of attributes which can be applied to any factory. [4] [5]

factory:statusdotitle{"Seeking for Full Time jobs"}trait:internationaldointernational{true}endtrait:residentdointernational{false}endtrait:comp_scidocomp_sci{true}endtrait:electricaldocomp_sci{false}endfactory:comp_sci_international_student,traits:[:international,:comp_sci]factory:electrical_resident_student,traits:[:resident,:electrical]end

Alias

Factory Bot allows creating aliases for existing factories so that the factories can be reused. [4]

factory:user,aliases:[:student,:teacher]dofirst_name{"John"}endfactory:noticedoteacher# Alias used ''teacher'' for ''user''title{"Office Hours"}endfactory:notificationdostudent#Alias used student for user title{"Lecture timings"}end

Sequences

Factory Bot allows creating unique values for a test attribute in a given format. [4]

FactoryBot.definedofactory:titledosequence(:name){|n|"Title #{n}"}# Title 1, Title 2 and so on...endend

Inheritance

Factories can be inherited while creating a factory for a class. This allows the user to reuse common attributes from parent factories and avoid writing duplicate code for duplicate attributes. Factories can be written in a nested fashion to leverage inheritance.

factory:userdoname{"Micheal"}factory:admindoadmin_rightstrueendendadmin_user=create(:admin)admin_user.name# Michealadmin_user.admin_rights# true

Parent factories can also be specified explicitly.

factory:userdoname{"Micheal"}endfactory:admin,parent::userdoadmin_user{true}end

Callback

Factory Bot allows custom code to be injected at four different stages: [4]

after(:build)
Code can be injected after the factory is built
before(:create)
Code can be injected before the factory is saved
after(:create)
Code can be injected after the factory is saved
after(:stub)
Code can be injected before the factory is stubbed

See also

Other Test libraries for Ruby

Related Research Articles

Eiffel is an object-oriented programming language designed by Bertrand Meyer and Eiffel Software. Meyer conceived the language in 1985 with the goal of increasing the reliability of commercial software development; the first version becoming available in 1986. In 2005, Eiffel became an ISO-standardized language.

Ruby (programming language) General-purpose programming language

Ruby is an interpreted, high-level, general-purpose programming language which supports multiple programming paradigms. It was designed with an emphasis on programming productivity and simplicity. In Ruby, everything is an object, including primitive data types. It was developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.

In object-oriented programming languages, a mixin is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depends on the language. Mixins are sometimes described as being "included" rather than "inherited".

Apache Groovy Programming language

Apache Groovy is a Java-syntax-compatible object-oriented programming language for the Java platform. It is both a static and dynamic language with features similar to those of Python, Ruby, and Smalltalk. It can be used as both a programming language and a scripting language for the Java Platform, is compiled to Java virtual machine (JVM) bytecode, and interoperates seamlessly with other Java code and libraries. Groovy uses a curly-bracket syntax similar to Java's. Groovy supports closures, multiline strings, and expressions embedded in strings. Much of Groovy's power lies in its AST transformations, triggered through annotations.

In class-based object-oriented programming, a constructor is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

Dependency injection Software programming technique

In software engineering, dependency injection is a design pattern in which an object or function receives other objects or functions that it depends on. A form of inversion of control, dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs. The pattern ensures that an object or function which wants to use a given service should not have to know how to construct those services. Instead, the receiving 'client' is provided with its dependencies by external code, which it is not aware of. Dependency injection helps by making implicit dependencies explicit and helps solve the following problems:

JRuby is an implementation of the Ruby programming language atop the Java Virtual Machine, written largely in Java. It is free software released under a three-way EPL/GPL/LGPL license. JRuby is tightly integrated with Java to allow the embedding of the interpreter into any Java application with full two-way access between the Java and the Ruby code.

A web framework (WF) or web application framework (WAF) is a software framework that is designed to support the development of web applications including web services, web resources, and web APIs. Web frameworks provide a standard way to build and deploy web applications on the World Wide Web. Web frameworks aim to automate the overhead associated with common activities performed in web development. For example, many web frameworks provide libraries for database access, templating frameworks, and session management, and they often promote code reuse. Although they often target development of dynamic web sites, they are also applicable to static websites.

WEBrick is a Ruby library providing simple HTTP web servers. WEBrick was primarily written by Masayoshi Takahashi and Yuuzou Gotou, with contributions from other developers via the open-source model of software development. It uses basic access authentication and digest access authentication for different kinds of servers that it can create - HTTP based server, HTTPS server, proxy server and virtual-host server. Construction of several non-HTTP servers such as the Day Time Server which uses the Daytime Protocol rather than the HTTP is also facilitated by WEBrick. It is used by the Ruby on Rails and Padrino frameworks to test applications in a development environment as well as production mode for small loads. It is now a part of Ruby standard library.

Embedded Ruby is a templating system that embeds Ruby into a text document. It is often used to embed Ruby code in an HTML document, similar to ASP and JSP, and PHP and other server-side scripting languages. The templating system of eRuby combines Ruby code and plain text to provide flow control and variable substitution, thus making the combined code easier to maintain.

A monkey patch is a way for a program to extend or modify supporting system software locally.

Chicken (Scheme implementation) Scheme-based programming language implementation

Chicken is a programming language, specifically a compiler and interpreter which implement a dialect of the programming language Scheme, and which compiles Scheme source code to standard C. It is mostly R5RS compliant and offers many extensions to the standard. The newer R7RS standard is supported through an extension library. Chicken is free and open-source software available under a BSD license. It is implemented mostly in Scheme, with some parts in C for performance or to make embedding into C programs easier.

The syntax of the Python programming language is the set of rules that defines how a Python program will be written and interpreted. The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages.

Visual Basic (classic) Event-driven programming language

The original Visual Basic is a third-generation event-driven programming language from Microsoft known for its Component Object Model (COM) programming model first released in 1991 and declared legacy during 2008. Microsoft intended Visual Basic to be relatively easy to learn and use. Visual Basic was derived from BASIC and enables the rapid application development (RAD) of graphical user interface (GUI) applications, access to databases using Data Access Objects, Remote Data Objects, or ActiveX Data Objects, and creation of ActiveX controls and objects.

RSpec is a computer domain-specific language (DSL) testing tool written in the programming language Ruby to test Ruby code. It is a behavior-driven development (BDD) framework which is extensively used in production applications. The basic idea behind this concept is that of test-driven development (TDD) where the tests are written first and the development is based on writing just enough code that will fulfill those tests followed by refactoring. It contains its own mocking framework that is fully integrated into the framework based upon JMock. The simplicity in the RSpec syntax makes it one of the popular testing tools for Ruby applications. The RSpec tool can be used by installing the rspec gem which consists of three other gems, namely rspec-core, rspec-expectation and rspec-mock.

Padrino (web framework)

Padrino is a free and open-source web framework, written in Ruby and based on Sinatra. It is an alternative to other Ruby web frameworks such as Ruby on Rails, Merb, Nitro and Camping. It is dependent on the Rack web server interface.

Mass assignment is a computer vulnerability where an active record pattern in a web application is abused to modify data items that the user should not normally be allowed to access such as password, granted permissions, or administrator status.

Capybara is a web-based test automation software that simulates scenarios for user stories and automates web application testing for behavior-driven software development. It is written in the Ruby programming language.

In the computing world, where software frameworks make life of developer easier, there are problems associated with it which the developer does not intend. Software frameworks use Object Relational Mapping (ORM) tool or Active Record Pattern for converting data of different types and if the software framework does not have a strong mechanism to protect the fields of a class, then it becomes easily exploitable by the attackers. These frameworks allow developers to bind parameters with HTTP and manipulate the data externally. The HTTP request that is generated carries the parameters that is used to create or manipulate objects in the application program.

Bogus is a Ruby API library used for minimizing risks involved in isolated unit testing. It was initially released in July 2012 by rubygems.org. Through Bogus, a piece of code can be tested in a fast and safe manner, without any actual integration with external programs. Bogus cannot mock or stub methods not present in the required external environment.

References

  1. "Project Naming History". github.com/thoughtbot/factory_bot.
  2. "Waiting For a FactoryGirl". Thoughtbot Blog.
  3. "Rails Testing". hiringthing.com.
  4. 1 2 3 4 5 "Getting Started". rubydoc.info/gems/factory_bot.
  5. "Traits". Thoughtbot Blog.