← Back to Upcase

Best way to create Factory so it is available for multiple tests?

(Jason Pierce) #1

I have several tests that need a FactoryGirl factory to be created. So now I have create :review in several RSpec tests. However, when I run the entire test suite I get the following error:

Failure/Error: create :review
Validation failed: Slug has already been taken

What is the best way to create :review so it is available to multiple tests? Or should I be doing it differently within each test?

(Andy Waite) #2

If your app is set up correctly, the data should be cleared between each test provided set_transactional_fixtures is true, so this should only be a problem if you need to create more than one review within a single test. Is that the case?

(Jason Pierce) #3

I do not have set_transactional_fixtures set any where that I can see. Where should that be set? And no, I only need to create one review for each test.

(Jason Pierce) #4

So I checked test.log and saw the restaurant was being created twice for one of my tests. I removed the create :restaurant statement and it worked. However, I am not sure why. Shouldn’t the restaurant still need to be created?

(Andy Waite) #5

Sorry, I meant to write use_transactional_fixtures. When you set up rspec-rails it should be enabled by default: https://relishapp.com/rspec/rspec-rails/docs/transactions

Depending on how your factories are set up, the associations may be created automatically: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations