views:

78

answers:

2

In Rails, fixtures records seem to be inserted & deleted in isolation for a given model. I'd like to test having many objects/rows in one transaction, eg. to check uniqueness. How to do it?

+1  A: 

Are you saying you want to build a test to check the rails "validates_uniqueness_of" operator or that you want to test the logic of your own unique record? In the first case, I wouldn't bother, the Rails tests cover that. In the second case, I would create a test that creates a record that is the same as one in the fixtures.

In the broader sense of putting multiple saves into a single transaction, you can create your objects and then:

MyModel.transaction do
  model1.save
  model2.save
end

but I don't think this is the way to accomplish either of the things it seems that you want to do.

MattMcKnight
Actually I don't know how Rails tests automagically cover validates_uniqueness_of operator. I don't observe it. I have the same value of an unique attribute for different objects in a fixture. Tests happily pass and test database contains both conflicting rows when checked via console. It's stupid.
Wojciech Kaczmarek
+1  A: 

Fixtures are not validated. When you set them up they can be totally wrong and Rails won't complain until something blows up. It's a good idea to make sure your initial test DB (that is seeded with your fixtures) is in a valid state before tests are run.

For checking things like uniqueness, I would create the records on the fly and not rely on fixtures. Either create them right in your test case, or use something like FactoryGirl (which by the way, is a great way to clean up your tests and stop using fixtures completely).

foz
Thanks, FactoryGirl looks promising.
Wojciech Kaczmarek