2016-08-24 263 views
1

我想通过使用共享上下文来干我的RSpec请求规范。我想在共享上下文之间共享let变量,以便它们彼此继承和扩展。如何在共享上下文之间共享RSpec让变量?

Rspec.shared_context 'JSON request' do 
    let(:headers) do 
    { 
     'Accept' => 'application/json' 
    } 
    end 
end 

Rspec.shared_context 'Authenticated request' do 
    let(:headers) do 
    super().merge('Authorization' => "Bearer #{token}") 
    end 
end 

Rspec.describe 'user management' do 
    let(:token) { create(:oauth_token) } 

    include_context 'JSON request' 
    include_context 'Authenticated request' 

    it 'responds with a 200 ok' do 
    get '/user', headers: headers 
    expect(response).to have_http_status(:ok) 
    end 
end 

声明token作品如预期,但使用super()覆盖headers回报NoMethodError暗示super()为零。

回答

2

我不知道在let块中引用当前定义的let变量的值的方法。 (当我尝试它时,我得到“堆叠层太深”)。我会尽你所能做到这一点:

Rspec.shared_context 'JSON request' do 
    let(:common_headers) do 
    { 
     'Accept' => 'application/json' 
    } 
    end 
    let(:headers) { common_headers } 
end 

Rspec.shared_context 'Authenticated request' do 
    let(:headers) do 
    common_headers.merge('Authorization' => "Bearer #{token}") 
    end 
end 
+0

完美,谢谢! –