Search code examples
ruby-on-railsrspecsendwithus

Testing sendwithus_ruby with rspec


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?


Solution

  • 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: "[email protected]" },
            {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