Fixtures in mail preview
Asked Answered
M

1

6

Having the following mailer previewer code:

class RegistrationMailerPreview < ActionMailer::Preview

  # Preview this email at http://localhost:3000/rails/mailers/registration_mailer/welcome
  def welcome
    RegistrationMailer.welcome users(:one)
  end

end

(full file).

Which is unable to reach my fixtures (users(:one)), return a 500 error status and print out the following error:

NoMethodError: undefined method `users' for #RegistrationMailerPreview

Can we get fixtures entries from mailer previewer?

If yes, I would like to know how to do that.
I have seen that should be possible here, but I can't require test_helper in this file (I don't know why) and I don't understand the difference between ActionMailer::TestCase and ActionMailer::Preview.

If no, is there a way to preview the mail without sending as a parameter User.first, since I could do my tests on a machine on which there is no data filled in the database.

Mamiemamma answered 15/9, 2016 at 15:36 Comment(0)
P
-3

I don't know about the default fixture framework, but I can say using FactoryBot for my fixtures that I was able to use them in my mailer previews simply by prepending the build/create methods with FactoryBot. I didn't need to require anything at the top of the file. i.e.:

class RegistrationMailerPreview < ActionMailer::Preview
  def welcome
    user = FactoryBot.create(:user)
    RegistrationMailer.welcome(user)
  end
end

To answer your second question, you could also simply replace the fixture line above with user = User.new(firstname: "Joe"). That would create a new user to use in the preview without persisting it to the database.

Peptide answered 19/12, 2017 at 21:13 Comment(1)
I don't know why it's downvoted but I can guess - this presents FactoryBot as a solution vs. fixtures.Ringed

© 2022 - 2024 — McMap. All rights reserved.