2017-07-03 78 views
1

我將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 

我試圖整合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,紅寶石的寶石,但還沒有任何運氣。

是否有人有他們如何測試或測試的例子和解釋?我正在試着圍住它。

+0

從您的輸出中,似乎沒有調用send_message。一種方法是將WebMock設置爲允許連接到互聯網,編寫測試以便在調用Twilio API時通過。通過後,禁用網絡連接並對請求進行存根,以便您仍然有合格的測試但不會調用Twilio。 –

回答

0

我最終使用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在這裏非常有幫助。