How to test with RSpec if an email is delivered

后端 未结 8 1151
清酒与你
清酒与你 2020-12-25 11:09

I\'d like to test if an email is delivered if I call a controller method with :post. I\'ll use email_spec so I tried this snipped here: http://rubydoc.info/gems/email_spec/1

8条回答
  •  甜味超标
    2020-12-25 11:33

    Configure your test environment to accumulate sent mails in ActionMailer::Base.deliveries.

    # config/environments/test.rb
    config.action_mailer.delivery_method = :test
    

    Then something like this should allow you to test that the mail was sent.

    # Sample parameters you would expect for POST #create.
    def reservation_params
      { "reservation" => "Drinks for two at 8pm" }
    end
    
    describe MyController do
      describe "#create" do
        context "when a reservation is saved" do
          it "sends a confirmation email" do
            expect { post :create, reservation_params }.to change { ActionMailer::Base.deliveries.count }.by(1)
          end
        end
      end
    end
    

    Note that my example uses RSpec 3 syntax.

提交回复
热议问题