[RUBY] ActiveRecord :: RecordInvalid: Validation failed: Email has already been taken error in RSpec test

Rest assured that all tests have been successful with RSpec! When I push it and see the test result of CircleCI,

** Gyaaaa! !! A lot of tests have failed! !! ** **

Here is a part of the error statement


ActiveRecord::RecordInvalid:Validation failed: Email has already been taken

It is probable that validation failed and an error occurred in the second CircleCI test because the test data was not deleted (rolled back) and remained when the first test execution was completed. In other words, the email address was already registered, so when I ran the second test, I couldn't generate test data and it failed.

If it is a feature spec, you can solve this by inserting a gem called database_cleaner. If you insert this gem, it will roll back the DB at the end of the test.

However, the test I did was system specs. The system specs were introduced from RSpec 3.7 and roll back the test data DB by default. database_cleaner is not required.

But why wasn't it rolled back ... I was at a loss ...


This was done in an instant.


 RSpec.configure do |config|
  config.use_transactional_fixtures = true
  #↑ This sentence was false
~ (Omitted) ~

The transaction rollback setting was false. When I was using the feature specs, I set this to false when installing the database_cleaner gem, so I ran the system specs with that setting.

Just setting this change to true will only roll back the db, and the test will fail as well because the current test data still remains. After this, you need to reset the DB data in the test environment. ..

docker-compose run app rails db:migrate:reset RAILS_ENV=test

After doing this, the test passed successfully.

Thank you for reading to the end!

Outputs daily learning! !! We look forward to helping you even a little! Also, if you have any suggestions or impressions, I would be grateful if you could comment!

Recommended Posts

ActiveRecord :: RecordInvalid: Validation failed: Email has already been taken error in RSpec test
"Email has already been taken" problem and workaround in RSpec's Email uniqueness test