twilio_spec.rb 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. require 'rails_helper'
  2. RSpec.describe Channel::Driver::Sms::Twilio do
  3. it 'passes' do
  4. channel = create_channel
  5. stub_request(:post, url_to_mock)
  6. .to_return(body: mocked_response_success)
  7. api = channel.driver_instance.new
  8. expect(api.send(channel.options, { recipient: '+37060010000', message: message_body })).to be true
  9. end
  10. it 'fails' do
  11. channel = create_channel
  12. stub_request(:post, url_to_mock)
  13. .to_return(status: 400, body: mocked_response_failure)
  14. api = channel.driver_instance.new
  15. expect { api.send(channel.options, { recipient: 'asd', message: message_body }) }.to raise_exception(Twilio::REST::RestError)
  16. expect(a_request(:post, url_to_mock)).to have_been_made
  17. end
  18. private
  19. def create_channel
  20. FactoryBot.create(:channel,
  21. options: {
  22. account_id: account_id,
  23. adapter: 'sms/twilio',
  24. sender: sender_number,
  25. token: token
  26. },
  27. created_by_id: 1,
  28. updated_by_id: 1)
  29. end
  30. # api parameters
  31. def url_to_mock
  32. "https://api.twilio.com/2010-04-01/Accounts/#{account_id}/Messages.json"
  33. end
  34. def account_id
  35. 'ASDASDAS3213424AD'
  36. end
  37. def message_body
  38. 'Test'
  39. end
  40. def sender_number
  41. '+15005550006'
  42. end
  43. def token
  44. '2345r4erfdvc4wedxv3efds'
  45. end
  46. # mocked responses
  47. def mocked_response_success
  48. '{"sid": "SM07eab0404df148a4bf3712cb8b72e4c2", "date_created": "Fri, 01 Jun 2018 06:11:19 +0000", "date_updated": "Fri, 01 Jun 2018 06:11:19 +0000", "date_sent": null, "account_sid": "AC5989ff24c08f701b8b1ef09e1b79cbf8", "to": "+37060010000", "from": "+15005550006", "messaging_service_sid": null, "body": "Sent from your Twilio trial account - Test", "status": "queued", "num_segments": "1", "num_media": "0", "direction": "outbound-api", "api_version": "2010-04-01", "price": null, "price_unit": "USD", "error_code": null, "error_message": null, "uri": "/2010-04-01/Accounts/AC5989ff24c08f701b8b1ef09e1b79cbf8/Messages/SM07eab0404df148a4bf3712cb8b72e4c2.json", "subresource_uris": {"media": "/2010-04-01/Accounts/AC5989ff24c08f701b8b1ef09e1b79cbf8/Messages/SM07eab0404df148a4bf3712cb8b72e4c2/Media.json"}}'
  49. end
  50. def mocked_response_failure
  51. '{"code": 21211, "message": "The \'To\' number asd is not a valid phone number.", "more_info": "https://www.twilio.com/docs/errors/21211", "status": 400}'
  52. end
  53. end