0

我正在升级一个站点以使用设计,并且我有以下规格要测试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来指定如果你没有登录就不能这样做。但是,当我添加时,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)

那么,为什么当我明确调用get :index但不在共享示例组中时这会起作用?

4

1 回答 1

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
于 2013-11-08T00:39:26.380 回答