【问题标题】:How to test integration with the Twilio API using Minitest如何使用 Minitest 测试与 Twilio API 的集成
【发布时间】:2017-07-03 18:56:51
【问题描述】:

我将 Twilio-Ruby 集成到我的 Ruby 中,并创建了一些使用该 gem 发布到 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

我尝试将 WebMockMocha 与我的 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 的规格,但没有任何运气。

是否有人提供了他们如何测试或将要测试的示例和说明?我正试图绕过它。

【问题讨论】:

  • 从您的输出中,看来 send_message 没有被调用。您可以采取的一种方法是将 WebMock 设置为允许连接到 Internet,编写测试以使其在调用 Twilio API 时通过。通过后,禁用网络连接并存根请求,这样您仍然可以通过测试但不调用 Twilio。

标签: ruby-on-rails ruby twilio-api


【解决方案1】:

我最终使用 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记录成功调用。我使用了一个有效的电话号码发送到,以验证它是否正常工作。您将在下面的测试中看到一个示例电话号码。如果您使用此示例,请务必更改它。

 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 在这里非常有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2019-05-09
    相关资源
    最近更新 更多