2017-01-24 22 views
1

是否有可能做這樣的事情?RSpec之前在幫手

module MyHelper 
    before (:each) do 
    allow(Class).to receive(:method).and_return(true) 
    end 
end 

然後在我的測試中,我可以這樣做:

RSpec.describe 'My cool test' do 
    include MyHelper 
    it 'Tests a Class Method' do 
    expect { Class.method }.to eq true 
    end 
end 

編輯:這將產生以下錯誤:

undefined method `before' for MyHelper:Module (NoMethodError) 

基本上我有一個情況許多測試做了不同的事情,但一個共同的模型跨越了他們之後的反應_commit最終總是調用一個與API對話的方法。我不希望全球允許Class收到:method,有時候,我需要自己定義它以適應特殊情況......但我不想重複我的allow/receive/and_return,而是將它包裝在一個共同的幫助器中...

回答

3

您可以創建一個hook that is triggered via metadata,例如:type => :api

RSpec.configure do |c| 
    c.before(:each, :type => :api) do 
    allow(Class).to receive(:method).and_return(true) 
    end 
end 

而在你的規格:

RSpec.describe 'My cool test', :type => :api do 
    it 'Tests a Class Method' do 
    expect { Class.method }.to eq true 
    end 
end 

您也可以通過:type => :api個人it塊。

+0

完美的解決方案!:) –

+0

這指甲!謝謝@Stefan :) – Nick

1

有可能像你想叫shared_context

您可以用代碼創建共享文件這樣

shared_file.rb功能做的事情

shared_context "stubbing :method on Class" do 
    before { allow(Class).to receive(:method).and_return(true) } 
end 

然後,你可以包括你在你想要像這樣

your_spec_file.rb

require 'rails_helper' 
require 'shared_file' 

RSpec.describe 'My cool test' do 
    include_context "stubbing :method on Class" 
    it 'Tests a Class Method' do 
    expect { Class.method }.to eq true 
    end 
end 

塊所需的文件,這種情況下這將是更自然的RSpec的比你的包括/擴展模塊助手。這將是「RSpec方式」讓我們說。

+0

這僅適用於rspec 3.6+嗎? – Nick

+0

我想我是在rspec的舊版本;我得到這個錯誤:'未定義的方法'shared_context_metadata_behavior ='爲#(NoMethodError)' - 除此之外,這可能是最新的rspec的正確答案... – Nick

+1

不確定關於那個。我相信我在rspec 3.0中使用它。無論如何,你可以按照我的答案中的鏈接,選擇你的rspec版本,並找出該功能是否支持你的版本 – VAD

0

你可以分開的代碼爲shared_context並將其包含到例如組(未示例)就像這樣:

RSpec.describe 'My cool test' do 
    shared_context 'class stub' do 
    before (:each) do 
     allow(Class).to receive(:method).and_return(true) 
    end 
    end 

    describe "here I am using it" do 
    include_context 'class stub' 

    it 'Tests a Class Method' do 
     expect { Class.method }.to eq true 
    end 
    end 

    describe "here I am not" do 
    it 'Tests a Class Method' do 
     expect { Class.method }.not_to eq true 
    end 
    end 
end 

共享環境可以包含let,輔助功能&你需要的一切只是例子。 https://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-context