I have a big list of record (something like 20, could be more) with a has_many :through relations, which is a bit complicate and it looks ugly on yml. Factory_girl doesn't seems to give me the simplistic ability to just create the fixture with a AR based script (it's a lot shorter that way) any good recommendation on what I could do?
A:
You could open up your model again in your factories file and add a method to create the test records. Something like:
class User
after_create :create_records_for_testing
def create_records_for_testing
# code to create records
end
end
Of course that could cause confusion down the road because the model you're testing doesn't behave the same as the model you're using in your app. Maybe there's a better way?
eremite
2009-09-09 01:32:11
This is very evil! You could change other pars as well in your User model and break every test in the system (or make them all pass when they shouldn't). Don't monkey-patch our models for testing!
Ariejan
2009-09-09 14:42:53
A better idea might be to use something like this patch for Factory Girl: http://stackoverflow.com/questions/1506556/hasmany-while-respecting-build-strategy-in-factorygirl
eremite
2009-10-02 04:02:06
A:
Don't monkey patch! Use Factory Girl! (she's sweet):
Factory.define(:user) do |t|
t.factory { |a| a.assocation(:factory) }
end
Factory.define(:factory) do |t|
t.name "Test Factory"
end
In our specs do this:
before(:each) do
@factory = Factory(:factory)
20.times do
Factory(:user, :factory => @factory)
end
end
Ariejan
2009-09-09 14:44:54
You can also use Factory Girl's Sequences to generate unique factory names, or add user names and the like easily.
Ariejan
2009-09-09 14:45:29