factory_boy_ruby
Allows you to create factories for the non-active record classes like the business logic layer ones, to be able to generate testing instances from these classes for easy and DRY test writing.
Installation
Add the following in the gemfile:
gem 'factory_boy_ruby'
and run bundle install
Or install it manually from the shell:
gem install factory_boy_ruby
Getting started
First you need to require it, preferred doing this in the spec_helper
# spec/spec_helper.rb
require 'factory_boy'
and make a folder to put your factory code in eg. spec/factory_boy/factories, if you're using factory_girl load these factories after factory_girl factories to be able to use them. you can add these lines in the spec_helper to be able to load them
# spec/spec_helper.rb
Dir['./spec/factory_boy/factories/**/*.rb'].each { |f| require f }
or loading it in the factory_girl initializer would work as well
# initializer/factory_girl.rb
FactoryGirl.definition_file_paths.push(Pathname.new (File.join(Rails.root, 'spec/factory_boy')))
Sample
Sample factory for class VehilcesRetriever
class VehilcesRetriever
def initialize(provider_company, country, city, vehicle_type) ;
end
# factory_boy/factories/vehicles_retriever.rb
FactoryBoy.define do
factory :vehicles_retriever, class: VehilcesRetriever do
factory_girl :provider_company, factory: :company, create: true
factory_girl :country
vehicle_type { VehicleTypes.all.sample }
before(:build) do
FactoryGirl.create(:vehicle, provider_company: self.provider_company ,country: self.country, vehicle_type: self.vehicle_type)
end
end
end
To generate an instance from this factory:
FactoryBoy.build(:vehicles_retriever)