Rails 功能测试与固定装置失败并出现“Mysql::Error: Duplicate Entry”
因此,我们有用户模型的默认脚手架测试,具体来说:
test "should create user" do
assert_difference('User.count') do
post :create, :user => @user.attributes
end
assert_redirected_to user_path(assigns(:user))
end
我们有一个用户固定装置:
one:
email: [email protected]
name: Joe Smith
问题是测试失败:
1) 错误: test_should_create_user(UsersControllerTest): ActiveRecord::RecordNotUnique: Mysql::错误:重复条目 密钥 2 的“[电子邮件受保护]':INSERT INTO
用户
似乎发生的情况是,rails 加载了固定装置,然后尝试使用相同的“一”数据再次创建用户,并且唯一性约束失败。这都是有道理的。问题是,如果您需要从测试中创建的用户对象的固定装置文件中提取数据,并且使用相同的固定装置来预填充数据库,我们如何测试这一点?
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: [email protected]
name: Joe Smith
The problem is the test is failing:
1) Error:
test_should_create_user(UsersControllerTest):
ActiveRecord::RecordNotUnique:
Mysql::Error: Duplicate entry
'[email protected]' for key 2: INSERT
INTOusers
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最黑客的解决方案是将电子邮件参数更改为,以便将不同的电子邮件地址发送到创建操作。
然而,我认为更好、更长期的解决方案是改用 FactoryGirl 而不是固定装置。这样,您可以控制何时在测试数据库中创建记录,并且能够随着数据模型的发展调整 FactoryGirl 生成的内容。
然后,我将修改上述调用以将正确的参数发送到创建操作并使测试通过。
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.