Rails Functional Test With Fixtures Failing with "Mysql::Error: Duplicate entry"
So we have the default scaffold tests for the User model, specifically:
test "should create user" do
assert_difference('User.count') do
post :create, :user => @user.attributes
end
assert_redirected_to user_path(assigns(:user))
end
And we have a users fixture:
one:
email: test2@test.com
name: Joe Smith
The problem is the test is failing:
1) Error: test_should_create_user(UsersControllerTest): ActiveRecord::RecordNotUnique: Mysql::Error: Duplicate entry 'test2@test.com' for key 2: INSERT INTO
users
What seems to be happening is that rails loads the fixtures, and then tries to create the user AGAIN using the same "one" data and that uniqueness constraint is failing. This all makes sense. The question is how can we test this 开发者_JAVA技巧if you need to pull data from the fixtures file for the user object being created in the test, if that same fixture is used to prepopulate the database?
The hackiest solution would be to change the e-mail parameter to in order to send a different e-mail address to the create action.
However, I think a better and more long-term solution is to switch to using FactoryGirl as opposed to fixtures. This way, you can control when the records are created in the test database, as well as be able to adjust what FactoryGirl generates as your data model evolves.
I'd then modify the above call to send the proper parameters to the create action and have the test pass.
精彩评论