如何使用rspec shared_examples来测试我的控制器?

时间:2013-11-07 20:26:16

标签: ruby-on-rails rspec devise

我正在升级网站以使用设计,我有以下规格来测试SitesController

describe SitesController do
  let(:user)  { FactoryGirl.create(:user)  }
  let(:admin) { FactoryGirl.create(:user, :admin) }

  shared_examples "disallow get index" do
    get :index
    response.should_not be_success
  end

  context "with user signed in" do
    before(:each) { sign_in user }

    it "disallowes / with GET" do
      get :index
      response.should_not be_success
    end

    it_behaves_like "disallow get index"
  end

  context "with admin signed in" do
    before(:each) { sign_in admin }

    it "allowes / with GET" do
      get :index
      response.should be_success
    end
  end
end

我想添加一个没有用户登录的上下文,并使用共享示例disallow get index来指定如果您没有登录就不能这样做。但是,当我添加{{1我得到这个未定义的方法错误:

it_behaves_like "disallow get index"

那么,为什么当我明确地调用sites_controller_spec.rb:8:in `block (2 levels) in <top (required)>': undefined method `get' for #<Class:0x00000101746718> (NoMethodError) 而不是在共享示例组中时,这是否有效?

1 个答案:

答案 0 :(得分:0)

原来是一个非常简单的修复。我正在使用shared_examples替换it这样的块:

shared_examples "disallow get index" do
  get :index
  response.should_not be_success
end

shared_examples实际上是context块的“替代”。因此,您需要在it

中设置shared_examples个阻止
shared_examples "disallow get index" do
  it "fails on index" do
    get :index
    response.should_not be_success
  end
end