|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +RSpec.describe Mailtrap::EmailTemplates do |
| 4 | + subject(:templates) { described_class.new(api_key:) } |
| 5 | + |
| 6 | + let(:api_key) { 'correct-api-key' } |
| 7 | + let(:account_id) { 123 } |
| 8 | + let(:template_id) { 456 } |
| 9 | + |
| 10 | + def stub_api(method, path, status:, body: nil) |
| 11 | + stub = stub_request(method, "https://mailtrap.io#{path}") |
| 12 | + .to_return(status:, body:) |
| 13 | + yield |
| 14 | + expect(stub).to have_been_requested |
| 15 | + end |
| 16 | + |
| 17 | + describe '#all' do |
| 18 | + it 'returns templates list' do |
| 19 | + stub_api(:get, "/api/accounts/#{account_id}/email_templates", status: 200, body: '[{"id":1}]') do |
| 20 | + expect(templates.all(account_id:)).to eq([{ id: 1 }]) |
| 21 | + end |
| 22 | + end |
| 23 | + end |
| 24 | + |
| 25 | + describe '#create' do |
| 26 | + let(:params) { { name: 'Test', subject: 'Subj', category: 'Promotion', body_html: '<div>body</div>' } } |
| 27 | + |
| 28 | + it 'sends POST request with JSON body' do |
| 29 | + stub = stub_request(:post, "https://mailtrap.io/api/accounts/#{account_id}/email_templates") |
| 30 | + .with(body: params.to_json) |
| 31 | + .to_return(status: 201, body: '{"id":2}') |
| 32 | + expect(templates.create(account_id:, **params)).to eq({ id: 2 }) |
| 33 | + expect(stub).to have_been_requested |
| 34 | + end |
| 35 | + end |
| 36 | + |
| 37 | + describe '#update' do |
| 38 | + it 'sends PATCH request with JSON body' do # rubocop:disable RSpec/ExampleLength |
| 39 | + stub = stub_request(:patch, "https://mailtrap.io/api/accounts/#{account_id}/email_templates/#{template_id}") |
| 40 | + .with(body: { name: 'Updated' }.to_json) |
| 41 | + .to_return(status: 200, body: '{"id":2,"name":"Updated"}') |
| 42 | + expect(templates.update(account_id:, email_template_id: template_id, |
| 43 | + name: 'Updated')).to eq({ id: 2, name: 'Updated' }) |
| 44 | + expect(stub).to have_been_requested |
| 45 | + end |
| 46 | + end |
| 47 | + |
| 48 | + describe '#delete' do |
| 49 | + it 'sends DELETE request' do |
| 50 | + stub_api(:delete, "/api/accounts/#{account_id}/email_templates/#{template_id}", status: 204) do |
| 51 | + expect(templates.delete(account_id:, email_template_id: template_id)).to be true |
| 52 | + end |
| 53 | + end |
| 54 | + end |
| 55 | + |
| 56 | + describe 'error handling' do |
| 57 | + it 'raises authorization error' do |
| 58 | + stub_api(:get, "/api/accounts/#{account_id}/email_templates", status: 401, body: '{"errors":["Unauthorized"]}') do |
| 59 | + expect { templates.all(account_id:) }.to raise_error(Mailtrap::AuthorizationError) |
| 60 | + end |
| 61 | + end |
| 62 | + end |
| 63 | +end |
0 commit comments