2014-01-06 34 views
3

我是RSpec的新手,我只是想知道如何在控制器中的多個操作中重用上下文。具體來說,我有這樣的代碼:如何在RSpec中重用上下文?

describe "GET index" do 
    context "when authorized" do 
    ... 
    end 

    context "when unauthorized" do 
    it "denys access" 
    end 
end 

describe "GET show" do 
    context "when authorized" do 
    ... 
    end 

    context "when unauthorized" do 
    it "denys access" 
    end 
end 

... 

而且我想幹一點。每個操作的未授權上下文都是相同的,我如何重用它?

回答

5

共享的例子是您的朋友:

創建一個新的文件,像spec/shared/unauthorized.rb,包括它在你的spec_helper然後格式化是這樣的:

shared_examples_for "unauthorized" do 
    context "when unauthorized" do 
    it "denys access" 
    end 
end 

然後在您的規格:

include_examples "unauthorized" 

在每個描述塊中做這件事,你應該是金色的。

1

如果你使用流行的寶石Devise,您可以重新設計出這樣的映射:對spec/spec_helper.rb

require "spec_helper" 

describe Worksheet::CompanyController do 
    login_user_admin #<= this macros on /spec/support/controller_macros.rb 

    describe '#create' do 
    it 'admin login and create worksheet' do 
     post :create, worksheet_company: attributes_for(:"Worksheet::Company") 
     expect(response.status).to eq(302) 
     expect(response).to redirect_to(admin_root_path) 
    end 
    end 

創建並登錄admin_user spec/support/controller_macros.rb

module ControllerMacros 
    def login_user_admin 
    before(:each) do 
     @request.env["devise.mapping"] = Devise.mappings[:user_admin] 
     user_admin = FactoryGirl.create(:user_admin) 
     user_admin.confirm! 
     sign_in user_admin 
    end 
    end 
end 

RSpec.configure do |config| 
    ... 
    config.include Devise::TestHelpers, type: :controller 
    config.extend ControllerMacros, type: :controller 
    ... 
end 
相關問題