Learn How Factory Girl Works With Non-active Record 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:


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

class  Deal
attr_accessor  :title, :remainingQuantity, :price_amount

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

Factory.define :deal do |g|
g.title               "Whisky for $10"
g.remainingQuantity   20
g.price_amount        10

Step 4:

Now use this factory in your specs. For example

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.

3 thoughts on “Learn How Factory Girl Works With Non-active Record 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?

    1. 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.

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.