Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/#{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!

like image 287
Peter Ehrlich Avatar asked Dec 17 '22 11:12

Peter Ehrlich


1 Answers

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.

like image 76
John Hinnegan Avatar answered Dec 28 '22 09:12

John Hinnegan