1
votes

I'm trying to move a Rails 3 app that's using Fixtures over to Factory Girl and am not entirely sure on the proper approach to the database. (Note that I'm using Rspec for the tests).

I have a seeds.db that has data that is needed for my functional and integration tests, but when it comes to, say, the model test for my Role model, this seeded data might get in the way if I want to make an admin Role from the factory, but there's already an admin role in the database from my seed, and the name column must be unique. Additionally, any data I create in these model tests may interfere with my integration tests as I'll have additional data I'm not expecting.

So a couple questions I guess:

  1. What's the proper way to handle the database in my unit tests? I need the seeded data for the other tests, but they seem to be getting 'in the way' right now. Am I forced to make unique data with sequences, or is there a way load the seed data just for functional and integration tests, etc?

  2. Is there a proper way to clearing out the factory data so that it's just the seed data for the functional and integration tests?

Completely new to Factory Girl right now, and just want to learn it properly instead of hacking my way through it. Thanks for any input.

1

1 Answers

3
votes

The "proper" way to handle database data in tests is to make sure it's clean and consistent before every test is run. So many people (myself included) don't ever seed the database and instead use Factories.

Seeding the database also makes it harder to know what's going on and it causes you to make assumptions which many times ends up being incorrect. Instead, use factories to add just the data you need for your tests. It is a little bit of extra work but it's worth it because:

  1. Removes your assumptions
  2. Ensures a clean and consistent test environment
  3. Keeps all the data for the test right in the test

Plus, rspec has before(:each) and before(:all) so you can setup your data before running your tests. So it's not that much extra work.

But one thing that might trip you up at first is the fact that rspec will NOT clear the database between test runs when using before(:all) For that I usually just manually delete in a after(:all) block. So the rule of thumb I use is - whatever is created in before(:all) should be removed in after(:all)

Many people also use the database_cleaner gem for this but so far I haven't needed it.