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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With