如何使用Minitest测试与Twilio API的集成
问题描述:
我将Twilio-Ruby集成到我的Ruby中,并创建了一些使用该gem发布到API的方法。如何使用Minitest测试与Twilio API的集成
下面是我的TwilioMessage模型的方法在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
我试图整合WebMock和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 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在这里非常有帮助。
从您的输出中,似乎没有调用send_message。一种方法是将WebMock设置为允许连接到互联网,编写测试以便在调用Twilio API时通过。通过后,禁用网络连接并对请求进行存根,以便您仍然有合格的测试但不会调用Twilio。 –