John
John

Reputation: 394

How to test integration with the Twilio API using Minitest

I integrated Twilio-Ruby into my Ruby and created some methods that post to the API using that gem.

Here's an example of a method in my TwilioMessage model in Rails:

  def message(recepient_number, message_body = INSTRUCTIONS, phone_number = '++18889990000')
    account_sid = ENV['TWILIO_ACCOUNT_SID']
    auth_token = ENV['TWILIO_AUTH_TOKEN']

    @client = Twilio::REST::Client.new account_sid, auth_token
    @client.account.messages.create({
                                        :from => phone_number,
                                        :to => recepient_number,
                                        :body => message_body
                                    })
  end

I tried integrating WebMock and Mocha with my Minitest suite but I'm just not sure where to begin with that.

I tried using WebMock to block outgoing requests and stubbing it with:

stub_request(
        :post, "https://api.twilio.com/2010-04-01/Accounts/[ACCOUNT_ID]/Messages.json"
    ).to_return(status: 200)

in my setup block.

Then, in my test, I have:

  test "send message" do
    TwilioMessage.expects(:message).with('+18889990000').returns(Net::HTTPSuccess)
  end

In my test_helper file I have it set to only allow local connections.

WebMock.disable_net_connect!(allow_localhost: true)

But, I received:

Minitest::Assertion: not all expectations were satisfied
unsatisfied expectations:
- expected exactly once, not yet invoked: TwilioMessage(id: integer, from_number: string, to_number: string, message_body: text, message_type: string, twilio_contact_id: integer, created_at: datetime, updated_at: datetime).send_message('+18889990000')

I tried looking through the Specs for the Twilio-Ruby gem but haven't had any luck.

Does someone have an example and explanation of how they've tested or would test this? I'm trying to wrap my head around it.

Upvotes: 1

Views: 961

Answers (1)

John
John

Reputation: 394

I ended up using the Ruby Gem VCR for the test. Turns outs that it's super easy to setup.

At the top of the test file, I added:

require 'vcr'

VCR.configure do |config|
  config.cassette_library_dir = "test/vcr/cassettes"
  config.hook_into :webmock
end

VCR lets the call go through the first time and records the response to a fixture file specified in the config.cassette_library_dir line above.

Then, in the actual test, I used VCR.use_cassette to record the successful call. I used a valid phone number to send to in order to verify it was working as well. You'll see a sample phone number in the test below. Be sure to change that if you use this example.

 test 'send message' do
    VCR.use_cassette("send_sms") do
      message = TwilioMessage.new.message('+18880007777')
      assert_nil message.error_code
    end
  end

I found the RailsCast episode on VCR to be extremely helpful here.

Upvotes: 0

Related Questions