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

EDIT:基本的に

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

私はケースどこを持っている:これは、次のエラーを生成します多くのテストではさまざまなことが行われますが、一般的なモデルでは、 APIと通信するメソッドを常に呼び出して終了する_commit。私は完全にClass:methodを受け取ることを許可したくありません。時には、私はそれを特別なケースのために自分で定義する必要があります...しかし、私は許可/受信/ and_returnを繰り返す必要はなく、代わりに共通のヘルパー...

答えて

3

あなたは、たとえば:type => :apiため、hook that is triggered via metadataを作成することができます。

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 

ます。また、個々のitブロックに:type => :apiを渡すことができます。

+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 = 'for#(NoMethodError) ' - これ以外にも、これはおそらく最新のrspecの正しいaswerです... – 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

関連する問題