RSpec 3.4 / Rails 4.2:如何测试包含button_to的视图

时间:2016-05-10 21:57:16

标签: ruby-on-rails-4 rspec rspec-rails rspec3

我正在使用Rails 4.2和RSpec 3.4。我正在尝试为包含<%= button_to ... %>删除按钮的视图编写视图测试。我的测试因此错误而失败:

Failures:

  1) projects/show.html.erb get secret project as nondisclosed devcomm user shows the obfuscated name and disclosed user
     Failure/Error: <%= button_to "Delete this project and reassign all children to parent", {}, method: "delete", data: { confirm: "Are you sure?" }, class: "btn btn-danger" %>

     ActionView::Template::Error:
       No route matches {:action=>"show", :controller=>"projects"}
     # ./app/views/projects/show.html.erb:13:in `_app_views_projects_show_html_erb___2105827750050220814_23458641445220'
     # ./spec/views/projects/show.html.erb_spec.rb:23:in `block (3 levels) in <top (required)>'
     # ------------------
     # --- Caused by: ---
     # ActionController::UrlGenerationError:
     #   No route matches {:action=>"show", :controller=>"projects"}
     #   ./app/views/projects/show.html.erb:13:in `_app_views_projects_show_html_erb___2105827750050220814_23458641445220'

测试如下:

require 'rails_helper'

RSpec.describe "projects/show.html.erb", type: :view do
  fixtures :users, :projects

  context "get secret project as disclosed user" do
    it "shows the unobfuscated name and disclosed user" do
      assign(:user, users(:nondevcomm1))
      assign(:project, projects(:secretproject2))

      render

      expect(rendered).to match "Secret project 2"
      expect(rendered).to match "Boo Wah, Another job title"
    end
  end

  context "get secret project as nondisclosed devcomm user" do
    it "shows the obfuscated name and disclosed user" do
      assign(:user, users(:devcomm1))
      assign(:project, projects(:secretproject2))

      render  ### This is where it fails

      expect(rendered).to match "Project 3"
      expect(rendered).to match "Boo Wah, Another job title"
    end
  end

end

第一次测试通过而第二次测试失败的原因是因为第一次测试中的用户是非默认的,并且视图具有条件,如果用户是devcomm,则只显示button_to。

我找到了this related StackOverflow question,但由于导致问题的按钮删除了记录,我想将其保留为按钮而不是链接,因此我不能将其更改为link_to。

关于如何测试包含button_to的视图的任何想法?

1 个答案:

答案 0 :(得分:1)

我发现了这个问题。在视图中,我没有提供行动的对象。我将<%= button_to ... %>更改为此,现在我的测试通过了:

<%= button_to "Delete this project and reassign all children to parent", @project, method: "delete", data: { confirm: "Are you sure?" }, class: "btn btn-danger"
%>