Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test with RSpec if an email is delivered

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.2.1/file/README.rdoc#Testing_In_Isolation

But it doesn't work, because I pass an instance of the model-object to the delivery-method and the instance is saved before the delivery.

I tried to create an other instance of the model-object, but then the id isn't the same.

My controller-method looks like this:

def create     @params = params[:reservation]     @reservation = Reservation.new(@params)    if @reservation.save       ReservationMailer.confirm_email(@reservation).deliver       redirect_to success_path    else       @title = "Reservation"       render 'new'    end  end 

Do you have any idea to solve this?

like image 316
fossil12 Avatar asked Sep 02 '11 13:09

fossil12


People also ask

How do I run a RSpec test on a file?

Running tests by their file or directory names is the most familiar way to run tests with RSpec. RSpec can take a file name or directory name and run the file or the contents of the directory. So you can do: rspec spec/jobs to run the tests found in the jobs directory.

What are RSpec tests?

RSpec is a testing tool for Ruby, created for behavior-driven development (BDD). It is the most frequently used testing library for Ruby in production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool which you can start using rather quickly.


2 Answers

Assuming your test environment is set up in the usual fashion (that is, you have config.action_mailer.delivery_method = :test), then delivered emails are inserted into the global array ActionMailer::Base.deliveries as Mail::Message instances. You can read that from your test case and ensure the email is as expected. See here.

like image 154
Chowlett Avatar answered Sep 28 '22 07:09

Chowlett


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.

like image 33
Dennis Avatar answered Sep 28 '22 07:09

Dennis