将 validates_uniqueness_of 添加到模型会导致功能测试失败
尝试在 Rails 3 中制作一个简单的应用程序。
如果我使用 rails gscaffold team name:string && 创建团队模型rake db:migrate
,然后运行 rake
,我从预构建的测试中获得了成功。
如果我只是将 validates_uniqueness_of :name
添加到团队模型中。功能测试失败,
1) Failure:
test_should_create_team(TeamsControllerTest) [/test/functional/teams_controller_test.rb:20]:
"Team.count" didn't change by 1.
<3> expected but was
<2>.
我修改了tests/fixtures/teams.yml,如下所示:
one:
name: MyString
two:
name: MyString2
测试仍然失败。
没有比这更基础的了;我错过了什么?
Trying to make a simple application in rails 3.
If I create a team model with rails g scaffold team name:string && rake db:migrate
, then run rake
, I get success from the prebuilt tests.
If I simply add validates_uniqueness_of :name
to the team model. The functional tests fail with
1) Failure:
test_should_create_team(TeamsControllerTest) [/test/functional/teams_controller_test.rb:20]:
"Team.count" didn't change by 1.
<3> expected but was
<2>.
I modified tests/fixtures/teams.yml to look like this:
one:
name: MyString
two:
name: MyString2
The test still fails.
It can't get much more basic than this; what have I missed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
夹具基本上代表数据库中的模型实例。
如果您查看 test/function/teams_controller_test.rb 的顶部,您会看到
,然后在失败的功能测试中,您将看到
这就是正在发生的事情:您正在尝试创建一个具有与“the球队赛程名为:one”。由于两者具有相同的名称(因为它们具有完全相同的属性),因此唯一性验证失败。
尝试用此替换您的设置块
现在您将创建一个名为“唯一名称”的新团队(根据赛程,该团队不在数据库中),并且您的测试将通过。
Fixtures basically represent model instances that are in the database.
If you look at the top of test/functional/teams_controller_test.rb you'll see
and then in your failing functional test you'll have
This is what's happening: you're trying to create a new team with the same attributes as "the team fixture named :one". Since both would have the same name (since they have the exact same attributes), the uniqueness validation is failing.
Try replacing your setup block with this
Now you'll be creating a new team with the name 'unique name' (which isn't in the database according to the fixtures), and your test will pass.