Jimmy Baker
Jimmy Baker

Reputation: 3255

Rails 5.1 System Test Fixtures and Database Cleanup

Are rails 5.1 system tests supposed to reset the test database with original fixture data between each test?

This is not happening for me even between completely different test classes. One of my system tests is:

test 'delete thing' do
  # deletes a thing from the fixture data
end

then I have another test that just looks to see if the thing is there

test 'view thing' do
  # tries to view the thing
end

The test passes if the "view thing" test is ran first. If the "delete thing" test runs first then when my system test tries to view the thing then it fails.

I thought Rails system tests were resetting the data just like all the other tests. Is this not the case? Am I missing something?

Upvotes: 3

Views: 1497

Answers (3)

Jimmy Baker
Jimmy Baker

Reputation: 3255

Solved this one by changing the number of workers in our config/puma.rb file to 0 instead of 1.

Changing

workers ENV.fetch("WEB_CONCURRENCY") { 1 }

to

workers ENV.fetch("WEB_CONCURRENCY") { 0 }

fixed the issue for us.

Upvotes: 2

O. elegans
O. elegans

Reputation: 11

I have just been dealing with this exact issue this morning, and I think I have figured it out.

This doc on fixtures helped me a bit: http://api.rubyonrails.org/v5.1.4/classes/ActiveRecord/FixtureSet.html.

For me though, I just had to make sure i was using the ModelName.method approach when my test involved modifying data (like adding and deleting records) as this interacts with the test database and does not change your fixtures. At first I was using the fixture_name.method for both reading and writing, and that led to unexpected results.

So for example, with a model of Blog and a fixture file blogs.yml with one record in it (hashed to key = :one):

test "view blog" do
  get blog_path blogs(:one).id
  assert_response :success

  *OR*
  get blog_path Blog.first.id
  assert_response :success
end

But if modifying, stick with the second approach:

test "delete blogs" do
  assert_equal 1, Blog.count
  assert_equal Blog.first.id, blogs(:one).id
  Blog.destroy_all
  assert_equal 0, Blog.count
  assert_raises(NoMethodError) { Blog.first.id }
  assert_nothing_raised { blogs(:one).id }
end

test "before_or_after_delete_blogs" do
  assert_equal 1, Blog.count
  assert_equal Blog.first.id, blogs(:one).id
end

Both of those should pass.

Apologies if my explanation is off base. If that's the case, could you provide a little more context with your example?

Upvotes: 1

Sam
Sam

Reputation: 33

I use the gem database_cleaner. Not sure if that's exactly the answer to your problem.

Also this could help? rake db:test:prepare

Not too sure if your issue but hopefully that helps

Upvotes: 0

Related Questions