2016-10-09 38 views
2

我在使用RSpec中的共享示例定义的变量时遇到了问题。这是我的测试:RSpec不能在共享示例中使用定义的变量

RSpec.shared_examples "check user logged in" do |method, action, params| 
    it "redirects to the sign in page if the user is not logged in" do 
    send(method, action, params) 
    expect(response).to redirect_to(signin_url) 
    end 
end 

RSpec.describe UsersController, type: :controller do 
    describe "GET #show" do 
    let(:user) { FactoryGirl.create(:user) } 
    let!(:show_params) do 
     return { id: user.id } 
    end 

    context "navigation" do 
     include_examples "check user logged in", :get, :show, show_params 
    end 
    end 
end 

在测试中,我正在检查以确保用户需要在可以执行操作之前登录。我收到以下错误信息:

的method_missing':show_params上不可为例组

我需要做什么改变,使show_params访问?我试过用it_behaves_like而不是include_examples,但没有运气。我也尝试删除context "navigation"块无济于事。我需要跨多个控制器和动作执行此检查,因此似乎共享示例可能是重用代码的正确方法。

回答

3

这里的问题是在示例之外调用memoized let helper show_params

RSpec.describe UsersController, type: :controller do 
    let(:user) { FactoryGirl.create(:user) } 
    describe "GET #show" do 
    let(:action) { get :show, id: user } 
    it_should_behave_like "an authorized action" 
    end 
end 

RSpec.shared_examples "an authorized action" do 
    it "denies access" do 
    action 
    expect(response).to redirect_to(signin_url) 
    end 
end 

这是一个非常强大的模式,让您使用一个约定优于配置的做法,因为:

不是传递的则params的,你可以简单地从外部范围,其中要包括的例子引用letlast let always wins

RSpec.describe UsersController, type: :controller do 
    let(:user) { FactoryGirl.create(:user) } 
    describe "GET #show" do 
    let(:action) { get :show, id: user } 
    it_should_behave_like "an authorized action" 

    context "when signed in" do 
     before { sign_in user } 
     let(:action) { get :show, id: other_user } 
     context 'when viewing another user' do 
     it_should_behave_like "an authorized action" 
     end 
    end 
    end 
end 
+0

这工作很好!非常感谢你!我将共享示例放在一个单独的文件中('spec/controllers/shared_examples/authorized_action.rb'),在我的'spec/rails_helper.rb'中需要该目录,然后按照您的建议使用它! – Alexander