Rails Test Case: Rather than global fixtures is there any way to create fixtures for specific test case?

782 views Asked by At

I am using rails mintiest framework for writing test cases. I want to test the rails activerecord sql queries . To test activerecord queries, I am using rails fixtures that provide sample data for testing.

Initially, there were only two records in my fixture file users.yml as shown below:

user1:
  name: 'xxx'

user2:
 name: 'xyz'

Now with above data, I have written one test case that counts the number of records in the database are equal to 2 and it works fine. But the issue arises when I add one more user in the users.yml file required for other test case scenario, the count becomes 3 and test case fails.

I want to know, is there any way to create fixtures for a specific test case so that each test case will have its own fixture data?

If the answer is yes, then my test case that counts the number of records in the database won't fail even if I add extra user records in fixture file.

1

There are 1 answers

2
wendybeth On BEST ANSWER

There are a couple of ways to solve this problem - some people might recommend not using fixtures at all, and this may be worth looking into in the future. However, the most immediate solution: do not test the specific state of the database - ever. If you have your test set up as:

it 'should add one' do
  User.create(username: 'username')
  assert_equal 2, User.count
end

change it instead to simply count that the number of users has gone up by one:

it 'should add one' do
  count = User.count
  User.create(username: 'username')
  assert_equal count + 1, User.count
end

In fact, there is a custom assertion just for this use case:

http://apidock.com/rails/ActiveSupport/Testing/Assertions/assert_difference

it 'should add one' do
  assert_difference("User.count", 1) do
    User.create(username: 'username')
  end
end