nocksock
nocksock

Reputation: 5527

Querying another model from inside a model created by FactoryGirl

Just starting with FactoryGirl. I have a Model named Subscription. It has a method 'set_price` which apparently does some calculations. In order to do so, it has to ask another model for some values:

def set_price
  base_price = Option.find_by_key(:base_price).value.to_f
  # […] some calculations
end

When running my specs I get:

   NoMethodError:
            undefined method `value' for nil:NilClass

Which is quite logical since I didn't (yet?) create any Options.

Is FactoryGirl suited for this? Do I have to create Option fixtures in this case? Or just mock it?

Upvotes: 0

Views: 199

Answers (1)

Sam Peacey
Sam Peacey

Reputation: 6034

This will fail because there are no Options in the database. You can either create the option factory before calling set_price in the test (you'll need to make sure find_by_key(:base_price) will return your factory created option in this case), or you can as you say use a mock:

option = mock_model('Option', :value => 1)
Option.stub(:find_by_key).and_return(option)

The mock has the advantage that it will not touch the database, but it's potentially more brittle.

Upvotes: 1

Related Questions