【问题标题】:Are instance variables from the controller passed to the spec in Rails?控制器中的实例变量是否传递给 Rails 中的规范?
【发布时间】:2012-06-09 10:05:42
【问题描述】:

由于某种原因,我的规范没有通过。 @categories 似乎没有达到规范。

这是控制器:

class CategoriesController < ApplicationController
  def index
    @categories = Category.all
  end
end

还有我的规格:

require 'spec_helper'

describe CategoriesController do

  describe "GET #index" do
    category = FactoryGirl.create(:category)
    subject { get :index }
    it { @categories.should include category }
  end

end

错误:

Failure/Error: @categories.should include category
     NoMethodError:
       undefined method `include?' for nil:NilClass

【问题讨论】:

  • 实际错误是什么?

标签: ruby-on-rails ruby testing rspec controller


【解决方案1】:

不,但您可以使用 assigns 规范助手访问它们:

require 'spec_helper'

describe CategoriesController do

  describe "GET #index" do
    category = FactoryGirl.create(:category)
    subject { get :index }
    it { assigns(:categories).should include category }
  end

end

【讨论】:

    【解决方案2】:

    实例变量是在控制器而不是规范中设置的。

    如果你想确保在控制器中设置了一个实例变量,那么你应该使用

    assigns(:categories).should include category
    

    更多信息可在此处获得:

    https://www.relishapp.com/rspec/rspec-rails/v/2-10/docs/controller-specs

    【讨论】:

      猜你喜欢
      • 2015-11-02
      • 1970-01-01
      • 2015-12-14
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多