控制器中的实例变量是否传递给Rails中的规范?

时间:2012-06-09 10:05:42

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

出于某种原因,我的规格没有通过。似乎@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

2 个答案:

答案 0 :(得分:3)

不,但您可以使用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

答案 1 :(得分:0)

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

如果要确保在控制器中设置实例变量,则应使用

assigns(:categories).should include category

更多信息请点击此处:

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

相关问题