View规范不会运行控制器before_action

时间:2013-08-30 15:38:32

标签: ruby-on-rails view rspec controller ruby-on-rails-4

我有这个失败的观点规范:

require 'spec_helper'

describe "ideas/edit" do
  before(:each) do
    @idea = assign(:idea, stub_model(Idea,
      :phase => 1,
      :brief => "MyText",
      :image => "MyString",
      :active => true,
      :activity_list => ["Science & Technology"]
    ))
  end

  it "renders the edit idea form" do
    render

    # Run the generator again with the --webrat flag if you want to use webrat matchers
    assert_select "form[action=?][method=?]", idea_path(@idea), "post" do
      assert_select "textarea#idea_brief[name=?]", "idea[brief]"
      assert_select "input#idea_industry[name=?]", "idea[industry]"
    end
  end
end

错误:

  1) ideas/edit renders the edit idea form
     Failure/Error: render
     ActionView::Template::Error:
       undefined method `empty?' for nil:NilClass
     # ./app/views/ideas/_long_form.html.erb:27:in `block in _app_views_ideas__long_form_html_erb___781758430_98755320'
     # ./app/views/ideas/_long_form.html.erb:1:in `_app_views_ideas__long_form_html_erb___781758430_98755320'
     # ./app/views/ideas/edit.html.erb:3:in `_app_views_ideas_edit_html_erb__967817323_98657300'
     # ./spec/views/ideas/edit.html.erb_spec.rb:15:in `block (2 levels) in <top (required)>'

这是渲染表单的相关行。 @categories变量在控制器中初始化,但在运行规范时由于某种原因是零。

<div class="field">
  <%= f.label :category_list, "Categories" %>
  <%= f.select :category_list, @categories, {selected:@idea.category_list}, {:multiple => true, :style => "height:180px;"} %>
</div>

在我的控制器中我有:

before_action :set_categories, only: [:edit, :update]
...
def set_categories
      @categories = [
        "Arts & Entertainment",
        "Science & Technology",
        "Business & Finance",
        "Software & Internet",
        "Retail",
        "Education",
        "Energy & Utilities",
        "Food & Health",
        "Media & Communications",
        "Other"
      ]
    end

在排除故障时我尝试删除“only:”限制并收到相同的错误。

有趣的是,如果我将以下行添加到其before(:each)块中,则规范通过:

@categories = "Other"

似乎规范没有在控制器中运行before_action。这是预期的行为吗?我在这里错过了什么?

1 个答案:

答案 0 :(得分:0)

此帖子表明视图规范旨在与控制器隔离运行,并且必须在规范中设置变量:http://www.arailsdemo.com/posts/37“实例变量和渲染视图”

我在规范

中的“渲染”之前添加了这一行
assign :categories, []