【问题标题】:Rspec feature test issueRspec 功能测试问题
【发布时间】:2014-04-11 00:17:51
【问题描述】:

spec/features/album_spec.rb:

feature "Album Pages" do

  given(:album) { create(:album) } # by Factory_Girl

  scenario "Edit album" do
    visit edit_album_path album

    fill_in "Name", with: "bar"
    expect {click_button "Update Album"}.to change(Album.last, :name).to("bar")
  end

end

错误:

  1) Album Pages Edit album
     Failure/Error: expect {click_button "Update Album"}.to change(Album.last, :name).to("bar")
       name should have been changed to "bar", but is now "Gorgeous Granite Table"
     # ./spec/features/albums_spec.rb:27:in `block (2 levels) in <top (required)>'

应用程序运行良好,如果我单击按钮,它会重定向到专辑的网站,其名称显示为&lt;h1&gt;。我试过这个:

  scenario "Edit album" do
    visit edit_album_path album

    fill_in "Name", with: "bar"
    click_button "Update Album"
    save_and_open_page
    #expect {click_button "Update Album"}.to change(Album.last, :name).to("bar")
  end

我得到了一个页面,其中bar&lt;h1&gt;,所以我不知道我的测试出了什么问题,我可以在 test.log 中看到:

SQL (0.7ms)  UPDATE "albums" SET "name" = ?, "updated_at" = ? WHERE "albums"."id" = 1  [["name", "bar"], ["updated_at", Fri, 11 Apr 2014 11:30:00 UTC +00:00]]

有什么想法吗?

【问题讨论】:

  • 我假设你在 github 上的某个地方有我可以查看的代码。
  • 对,对:here.

标签: ruby-on-rails rspec


【解决方案1】:

您需要您的更改验证也被阻止,如下所示:

scenario "Edit album" do
  visit edit_album_path album
  fill_in "Name", with: "bar"
  expect{click_button "Update Album"}.to change{Album.last.name}
end

【讨论】:

  • 效果很好!请阅读我自己的答案。我会很感激一些 cmets。
【解决方案2】:

阅读drKreso's 的答案后,我阅读了gems/rspec-expectations-.../lib/rspec/matchers.rbchange 有很多有用的例子。

您可以传递接收者和消息,也可以传递块,但不能同时传递两者。

我找到了另一种方法:

  scenario "Edit album" do

    @album = album
    visit edit_album_path @album    
    fill_in "Name", with: "bar"    

    expect{
      click_button "Update Album"
      @album.reload
      }.to change(@album, :name).to("bar")
  end

但即使现在我仍然很困惑为什么它在第一种方式上不起作用。因此,如果reload 是这里的关键,那么change 是否会在某处为传递的接收者调用它?我没能走得这么深。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 2013-08-31
    • 1970-01-01
    相关资源
    最近更新 更多