ruby-on-rails - Controller 中的实例变量是否传递到 Rails 中的规范?

标签 ruby-on-rails ruby testing rspec controller

出于某种原因,我的规范没有通过。看来 @categories 没有达到规范。

这是 Controller :

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

最佳答案

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

关于ruby-on-rails - Controller 中的实例变量是否传递到 Rails 中的规范?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10960086/

相关文章:

ruby-on-rails - 服务器已经在运行。检查 C :/Rails/tmp/pids/server. pid

Ruby - 将 block 传递给方法

ruby-on-rails - 从表单值 ruby​​ on rails 更新模型数据

mysql - 复杂的网络应用多线程测试(不加载)

javascript - 在脚本标签中使用 Ruby 变量

javascript - 使用 Rails 5 的 DOMContentLoaded 处理程序

ruby-on-rails - 使用 Paperclip 解析电子邮件附件 - 可能没有临时文件?

ruby-on-rails - 为什么根路由不能与 users#show 一起使用?

performance - 是否可以使用表达式在 JMeter 中创建用户定义变量?

ruby-on-rails - 错误测试创建操作