Factory_girl with NonActiveRecord classes

In earlier post you have seen how to test active record associations with factory girl. Now you will learn how factory girl works with non-active record classes. When you want to test external API responses, this will be useful.  By using this you can build no of responses at a time and test, how system will handle inputs. It is as similar as to working factory girl with active record classes. Now here is the way

Step1:

First you need define class and attributes of the class. For example

#spec/support/models/deal.rb
class  Deal
   attr_accessor  :title, :remainingQuantity, :price_amount
end

Step 2:

Create a directory called ‘models’ inside ‘spec/support’ directory and place this class.  Because of following line of code it will includes our class while test environment is loading.

# spec/spec_helper.rb
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

Step 3:

Now we have to create an object by using factory. Create a factory file in spec/factories directory as how we are writing factory file for a active record class. For example

#spec/factories/deal.rb
Factory.define :deal do |g|
    g.title               "Whisky for $10"
    g.remainingQuantity   20
    g.price_amount        10
end

Step 4:

Now use this factory in your specs. For example

#spec/models/deal_spec.rb
deal = Factory.build(:deal)

It will return an object of class Deal. Now it works as a normal ruby object and we can apply our conditions on it. For more see factory_girl

I hope everyone enjoyed this article. Any comments would be welcome.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s