在Rspec中测试视图,未定义的方法收集

时间:2016-04-07 11:25:05

标签: ruby-on-rails ruby rspec

我在Rspec中测试视图时出现以下错误。

1)问题/新呈现新问题表单

Failure/Error: 
<div class="col-md-8 col-sm-8">
  <%= f.select :approval_status, options_for_select(@approval_statuses.collect { |as| [as[0].humanize, as[0]] }, selected: @problem.approval_status), {}, class: "form-control" %>
</div>
ActionView::Template::Error:
  undefined method `collect' for nil:NilClass

我在控制器操作中传递@approval_statuses。 它在视图中工作正常,但在测试用例中我收到此错误。

控制器操作:

def new
   @problem = Problem.new
   @approval_statuses = Problem.approval_statuses
   @visibilities = Problem.visibilities
end

在模型中

enum approval_status: {not_approved: 0, approved: 1}

在new.html.erb_spec.rb

require 'rails_helper'

RSpec.describe "problems/new", type: :view do
  before(:each) do
  assign(:problem, Problem.new())
  end

  it "renders new problem form" do
   render
   assert_select "form[action=?][method=?]", problems_path, "post" do
   end

  end
end

1 个答案:

答案 0 :(得分:2)

您正在设置@problem实例变量,但不是@approval_statuses@visibilities,因此这些变量目前都是零。

RSpec.describe "problems/new", type: :view do
  before(:each) do
    assign(:problem, Problem.new)
    assign(:approval_statuses, Problem.approval_statues)
    assign(:visibilities, Problem.visibilities)
  end

  it "renders new problem form" do
    render

    assert_select "form[action=?][method=?]", problems_path, "post" do
    end

  end
end