2017-05-16 4 views
0

Je veux tester ma méthode qui fonctionne méthode Temp :: Service.run deux fois à l'intérieur:Rspec permettent et attendre la même méthode avec des arguments différents

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 

Je veux tester des arguments fournis à la deuxième appel méthode: exécuter avec le premier argument 'step2' tandis que je veux ignorer le premier appel de la même méthode: exécuter mais avec le premier argument 'step1'.

J'ai le test 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 

mais je suis erreur

expected: "step2" 
    got: "step1" 

(compared using ==) 

Comment utiliser correctement et permettre à attendre la même méthode?

+0

attentes vérifiera pour vous les paramètres envoyés, donc, vous n'avez pas besoin de faire ce que vous faites dans le bloc. Utilisez simplement 'expect (Temp :: Service) .pour recevoir (: run) .with ('step2'," arg3 "=>" v3 ") {true}'. – fanta

+0

Je veux faire des vérifications plus compliquées sur le second argument. Donc je l'ai fait avec le bloc. Comme ceci ' ['arg3', 'arg4']. Each do | arg_good | attendez (p [arg_good]). Not_to be_nil end' –

Répondre

1

On dirait que vous manquez les .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

ça marche! merci –

+0

@MaxIvak pas de problème! :) –