0

we use sendwithus ruby gem to send emails in our Rails app. (https://github.com/sendwithus/sendwithus_ruby). How can I test sending emails with rspec?

Mïchael Makaröv
  • 1,085
  • 12
  • 21

2 Answers2

3

This is a test using vcr library. Not pretty, but works. Share your ideas on how to improve it.

Ruby wrapper for testing:

class TestWithUs

  CASSETTES_PATH = 'fixtures/vcr_cassettes/'

  def initialize(name)
    @name = name
    @cassette_file = get_cassette_file(name)
  end

  def track(&block)
    File.delete(@cassette_file) if File.exist?(@cassette_file)
    VCR.use_cassette(@name) do
      block.call
    end
  end

  def results
    YAML.load(File.read @cassette_file)["http_interactions"]
  end

  private

  def get_cassette_file(name)
    CASSETTES_PATH + name + ".yml"
  end

end

Test File:

require 'spec_helper'
require 'vcr'

VCR.configure do |config|
  config.cassette_library_dir = "fixtures/vcr_cassettes"
  config.hook_into :webmock
  #config.ignore_request { |r| r.uri =~ /localhost:9200/ }
  config.ignore_localhost = true
end

describe 'messages sent to matt' do
  before do
    @test_with_us = TestWithUs.new("welcome_email")
    @test_with_us.track do

      # Usually it sends email on some kind of callback,
      # but for this example, it's straightforward

      SENDWITHUS.send_with(CONFIG.swu_emails[:welcome],
        { address: "user@example.com" },
        {company_name: 'Meow Corp'})
    end
  end

  it "Sends an email" do
    sendwithus_calls = @test_with_us.results.select {|c| c["request"]["uri"] == "https://api.sendwithus.com/api/v1/send"}
    expect(sendwithus_calls.count).to eq(1)
  end
end
Mïchael Makaröv
  • 1,085
  • 12
  • 21
2

Hmm, I know of three options here - which one is best will depend on what exactly you're testing and how your test environment is setup.

  1. Use rspec mocks to intercept the Sendwithus API calls and perform your own validation inside the mock.

  2. Use a network capture library (like VCR, https://github.com/vcr/vcr) to capture the API calls being made by the Sendwithus gem. You can then verify and assert that the captured requests are as you expect.

  3. Use a Sendwithus Test API Key and actually make API calls to your Sendwithus account. Test API Keys can be configured to never send email, or forward all email to a fixed email address. More info here: https://support.sendwithus.com/delivery/how_do_sendwithus_api_keys_work/

bvanvugt
  • 1,212
  • 1
  • 8
  • 15