NoMethodError: undefined method `assert_emails' in controller test
Asked Answered
A

2

11

According to the Rails documentation, the method assert_emails allows to transform the syntax :

assert_difference ->{ ActionMailer::Base.deliveries.size }, +1 do
  post :method_that_should_send_email
end

to

assert_emails 1 do
  post :method_that_should_send_email
end

which I find much better, because I don't have to copy paste the long syntax every time.

However I get the following error in my controllers tests when using the above code:

NoMethodError: undefined method `assert_emails'

I assume this is because the method is only available in mailers tests.

Is there a way to make it available to controllers tests too? Is there a good reason why this is not available by default? Is there a better way to test that calling a specific route results in sending a email?

Thanks.

Aggri answered 14/2, 2017 at 10:49 Comment(0)
A
16

I've just had the same problem when trying to use assert_emails in a regular test (not an ActionMailer::TestCase).

The helpers started working when I included ActionMailer::TestHelper to my test class.

class FooTest < ActiveSupport::TestCase
  include ActionMailer::TestHelper

  test '...' do
    assert_no_emails do
      # ...
    end
  end
end

I believe that should work in your controller tests as well.

Allopathy answered 5/7, 2017 at 18:37 Comment(1)
This also works below a Rspec.describe lineIllbred
B
1

** Using deliver_later **

If someone is sending the emails using deliver_later, then he can test it using the below code

include ActionMailer::TestHelper

test 'test deliver later' do
  assert_enqueued_emails 1 do
    ---code which runs deliver later--
  end

# Check the mailer name
  enqueued_jobs.first[:args][1] = 'my_mailer_method'
end
Brutish answered 3/3, 2022 at 10:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.