2013-09-08 2 views
0

저는 TDD와 Rspec을 처음 접했습니다. 내가하는 방법이 시험에서 호출되고 있는지 확인하는 방법을 알아 내려고 노력 해요 :Rspec에서 메소드 호출 모의 방법

$f = YAML.load_file("fixtures.yaml") 

describe YouTube do 
    data = $f["YouTube"] 
    subject { YouTube.new(data["uid"], data["token"], data["refresh"]) } 
    its(:token) { should == data["token"] } 

    context "when token is nil" do 
    subject(:without_token) { YouTube.new(data["uid"], nil, data["refresh"]) } 
    its(:token) { should_not be_nil } 
    it { YouTube.should_receive(:refresh_auth_token).with(data["refresh"]) } 
    end 

end 

그러나 그와 실패 :

) YouTube when token is nil Failure/Error: it { YouTube.should_receive(:refresh_auth_token).with(data["refresh"]) } ().refresh_auth_token("1/HBTNQ93otm1cSQH8kKauij3jO0kZQYfgH5J-hBtAP8k") expected: 1 time with arguments: ("1/HBTNQ93otm1cSQH8kKauij3jO0kZQYfgH5J-hBtAP8k") received: 0 times with arguments: ("1/HBTNQ93otm1cSQH8kKauij3jO0kZQYfgH5J-hBtAP8k") # ./lib/youtube/you_tube_test.rb:14:in `block (3 levels) in '

여기

module Authentication 
    include WebRequest 

    def refresh_auth_token(refresh_token) 
    "refreshing token" 
    end 
end 


class YouTube 
    include Authentication 
    attr_accessor :uid, :token, :refresh 

    def initialize(uid, token, refresh) 
    @uid = uid 
    @token = token 
    @refresh = refresh 

    # if token has expired, get new token 
    if @token == nil and @refresh 
     @token = refresh_auth_token @refresh 
    end 
    end 

end 

을 그리고 나의 테스트입니다

이 테스트에서 수행하려는 작업은 @token이 nil이고 이 제공된 경우 refresh_auth_tokeninitialize에 호출 될 때를 결정하는 것입니다. 이 mock과 stubs는 다소 혼란 스럽습니다.

답변

2

첫째, 당신은 any_instance를 사용하려면 :

YouTube.any_instance.should_receive(:refresh_auth_token).with(data["refresh"]) 

을 현재 클래스 메소드 refresh_auth_token 호출중인 경우에는 확인된다. 그것은 존재하지 않기 때문에 아닙니다.

코드가 생성자에서 실행되면 객체가 이미 스펙보다 먼저 제목 행에 작성되어 있으므로 해당 행은 호출을 catch하지 않습니다. any_instance`가 속임수를 썼는지`,

context "when token is nil" do 
    it "refreshed the authentation token" do 
     YouTube.any_instance.should_receive(:refresh_auth_token).with(data["refresh"]) 
     YouTube.new(data["uid"], nil, data["refresh"]) 
    end 
    end 
+0

감사 :

이 가장 쉬운 솔루션입니다. 'should_receive' 후에'YouTube.new'를 다시 호출하려고 생각했지만 작동하지 않았습니다. 이제는 그렇습니다. –

관련 문제