如何使用 Minitest 测试与 Twilio API 的集成

How to test integration with the Twilio API using Minitest

我将 Twilio-Ruby 集成到我的 Ruby 中,并使用 gem.

创建了一些 post 到 API 的方法

这是我在 Rails 中的 TwilioMessage 模型中的一个方法示例:

  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

我尝试将 WebMock and Mocha 与我的 Minitest 套件集成,但我不确定从哪里开始。

我尝试使用 WebMock 来阻止传出请求并将其存入:

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

在我的设置块中。

然后,在我的测试中,我有:

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

在我的 test_helper 文件中,我将其设置为仅允许本地连接。

WebMock.disable_net_connect!(allow_localhost: true)

但是,我收到了:

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')

我尝试查看 Twilio-Ruby gem 的规格,但没有任何运气。

有人有示例和解释说明他们如何测试或将要测试这个吗?我正在努力解决这个问题。

我最终使用 Ruby Gem VCR 进行测试。结果证明它非常容易设置。

在测试文件的顶部,我添加了:

require 'vcr'

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

VCR 让呼叫第一次通过并记录对上面 config.cassette_library_dir 行中指定的夹具文件的响应。

然后,在实际测试中,我使用VCR.use_cassette来记录调用成功。我使用了一个有效的 phone 号码来发送,以验证它是否正常工作。您将在下面的测试中看到示例 phone 号码。如果您使用此示例,请务必更改它。

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

我发现 RailsCast episode on VCR 在这里非常有用。