简体   繁体   中英

NoMethodError: undefined method `assert_emails' in controller test

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.

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.

** 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM