将 validates_uniqueness_of 添加到模型会导致功能测试失败

发布于 2024-10-02 23:32:50 字数 605 浏览 0 评论 0原文

尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那支青花 2024-10-09 23:32:50

夹具基本上代表数据库中的模型实例。

如果您查看 test/function/teams_controller_test.rb 的顶部,您会看到

setup do
  @team = teams(:one)
end

,然后在失败的功能测试中,您将看到

post :create, :team => @team.attributes

这就是正在发生的事情:您正在尝试创建一个具有与“the球队赛程名为:one”。由于两者具有相同的名称(因为它们具有完全相同的属性),因此唯一性验证失败。

尝试用此替换您的设置块

setup do
  @team = teams(:one)
  @team.name = 'unique name'
end

现在您将创建一个名为“唯一名称”的新团队(根据赛程,该团队不在数据库中),并且您的测试将通过。

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

setup do
  @team = teams(:one)
end

and then in your failing functional test you'll have

post :create, :team => @team.attributes

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

setup do
  @team = teams(:one)
  @team.name = 'unique name'
end

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文