twilio_spec.rb 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. require 'rails_helper'
  3. RSpec.describe Channel::Driver::Sms::Twilio do
  4. it 'passes' do
  5. channel = create_channel
  6. stub_request(:post, url_to_mock)
  7. .to_return(body: mocked_response_success)
  8. api = channel.driver_instance.new
  9. expect(api.deliver(channel.options, { recipient: '+37060010000', message: message_body })).to be true
  10. end
  11. it 'fails' do
  12. channel = create_channel
  13. stub_request(:post, url_to_mock)
  14. .to_return(status: 400, body: mocked_response_failure)
  15. api = channel.driver_instance.new
  16. expect { api.deliver(channel.options, { recipient: 'asd', message: message_body }) }.to raise_exception(Twilio::REST::RestError)
  17. expect(a_request(:post, url_to_mock)).to have_been_made
  18. end
  19. private
  20. def create_channel
  21. create(:channel,
  22. options: {
  23. account_id: account_id,
  24. adapter: 'sms/twilio',
  25. sender: sender_number,
  26. token: token
  27. },
  28. created_by_id: 1,
  29. updated_by_id: 1)
  30. end
  31. # api parameters
  32. def url_to_mock
  33. "https://api.twilio.com/2010-04-01/Accounts/#{account_id}/Messages.json"
  34. end
  35. def account_id
  36. 'ASDASDAS3213424AD'
  37. end
  38. def message_body
  39. 'Test'
  40. end
  41. def sender_number
  42. '+15005550006'
  43. end
  44. def token
  45. '2345r4erfdvc4wedxv3efds'
  46. end
  47. # mocked responses
  48. def mocked_response_success
  49. '{"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"}}'
  50. end
  51. def mocked_response_failure
  52. '{"code": 21211, "message": "The \'To\' number asd is not a valid phone number.", "more_info": "https://www.twilio.com/docs/errors/21211", "status": 400}'
  53. end
  54. end