2017-05-16 2 views
0
私は方法の温度を実行し、私の方法をテストしたい

と同じ方法を期待:RSpecのを許可し、異なる引数:: Service.run 2回、その中

module Temp 
    class Service 

    def self.do_job 
     # first call step 1 
     run("step1", {"arg1"=> "v1", "arg2"=>"v2"}) 


     # second call step 2 
     run("step2", {"arg3"=> "v3"}) 


    end 

    def self.run(name, p) 
     # do smth 

     return true 
    end 


    end 
end 

私は2回目の呼び出しに提供される引数をテストしたいですメソッド:最初の引数 'step2'を使って実行する 同じメソッドの最初の呼び出しを無視したいが、最初の引数 'step1'を実行する。

私はRSpecのテスト

RSpec.describe "My spec", :type => :request do 

    describe 'method' do 
    it 'should call' do 

     # skip this 
     allow(Temp::Service).to receive(:run).with('step1', anything).and_return(true) 

     # check this 
     expect(Temp::Service).to receive(:run) do |name, p| 
     expect(name).to eq 'step2' 

     # check p 
     expect(p['arg3']).not_to be_nil 

     end 


     # do the job 
     Temp::Service.do_job 

    end 
    end 
end 

持っているが、私はどのように正確に同じ方法を可能に使用し、期待するエラー

expected: "step2" 
    got: "step1" 

(compared using ==) 

を得ましたか。

+0

期待に欠けているように思えるので。単に 'expect(Temp :: Service).to(' run ').with(' step2 '、 "arg3" => "v3"){true} 'を使用してください。 – fanta

+0

2番目の引数より複雑なチェックを行いたい。だから私はブロックで作った。 このように ['arg3'、 'arg4']。each do | arg_good | expect(p [arg_good])。not_to be_nil end' –

答えて

1

はあなたがブロックでやっているものを行う必要はありません、あなたはあなたのために送られたパラメータをチェックします.with('step2', anything)

it 'should call' do 

    allow(Temp::Service).to receive(:run).with('step1', anything).and_return(true) 

    # Append `.with('step2', anything)` here 
    expect(Temp::Service).to receive(:run).with('step2', anything) do |name, p| 
    expect(name).to eq 'step2' # you might not need this anymore as it is always gonna be 'step2' 
    expect(p['arg3']).not_to be_nil 
    end 

    Temp::Service.do_job 
end 
+0

それが動作します!ありがとう –

+0

@MaxIvakいいえprob! :) –

関連する問題