2017-01-24 24 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