开发者

rspec mocking external api

New to TDD here, d'oh!

Here's what I want to test (ruby library), in brief:

 account = Twilio::RestAccount.new(ACCOUNT_SID, ACCOUNT_TOKEN)
    resp = account.request(
        "/#{API_VERSION}/Accounts开发者_JS百科/#{ACCOUNT_SID}/SMS/Messages",
        'POST',
        smsInfo
    )

And here's test code attempt:

describe Text do
  it "should call the Twilio API with credentials" do
    #pending "mocking api although not passed in.."
    t = mock(Twilio::RestAccount)
    twapi = mock("new twapi").should_receive(:request).and_return(Net::HTTPSuccess)
    t.stub(:new).and_return(twapi)

    Twilio::RestAccount.should_receive(:new)

    sms = Factory.create(:boring_sms)
    sms.send_sms
  end
end

which generates the error: undefined method `request' for nil:NilClass

Am I taking the right approach? thanks!


With Twilio and other external services, I also consider using VCR. http://relishapp.com/myronmarston/vcr

The upside is that you get it working once with manual testing, and it's basically verifying you don't mess anything up. Downside is that any time you touch code tested by VCR, you often have to re-test everything manually that's tested by VCR. Something else to consider.


You're stubbing new with 0 parameters, when you do this:

t.stub(:new).and_return(twapi)

But your test is:

Twilio::RestAccount.new(ACCOUNT_SID, ACCOUNT_TOKEN)

which is new with 2 params.

try:

t.should_receive(:new).once.with(any_args()).and_return(twapi)

and remove:

Twilio::RestAccount.should_receive(:new)


Check out webmock. That's really what you want to use for something like this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜