Factory_girl with Non-ActiveRecord classes

In earlier post we have seen how to test active record associations with factory girl. Now we will learn how factory girl works with non-active record classes. When we want to test external API responses, this will be useful.  By using this we 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
This entry was posted in Ruby on Rails, Tutorials and tagged , . Bookmark the permalink.

3 Responses to Factory_girl with Non-ActiveRecord classes

  1. Thanks Siva, very helpful.

    Question: why did you put the Deal class into spec/support/models? Wouldn’t this have worked just as well with the Deal class (using ActiveRecord::Bas or not) located in the app/models directory?

    • Siva Gollapalli says:

      Just to distinguish the file from other files, I have created ‘models’ directory and placed this file(see the step2 also). It works if you put in ‘app/models’ as well.

  2. Very helpful. Thanks. for writing this.

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