user3576036
user3576036

Reputation: 1425

NoMethodError: undefined method `mail' for main:Object on rails console

I am trying to test the working of mailer. Normally on rails I first test my code logic on console level and then once it is successful I put it into the real source code. I am trying to do the same while working on ApplicationMailer. I followed some other solution and first ran the following on rails console to first set up the ActionMailer

ActionMailer::Base.delivery_method = :smtp 
ActionMailer::Base.smtp_settings = {
  address: 'smtp.gmail.com', 
  port: 587, 
  domain: 'gmail.com',
  authentication: 'plain', 
  enable_starttls_auto: true, 
  user_name: '***********',
  password: '******'
}

and then I ran my code:

y.include? x
  if true
    @receiver = Model.where(category_id: "#{x}").pluck(:email)
    mail(to: @receiver, subject: @subject)
  end

I'm getting the following error:

NoMethodError: undefined method `mail' for main:Object
    from (irb):19

Could somebody please tell me how make this work on rails console?

Upvotes: 3

Views: 4753

Answers (2)

kronn
kronn

Reputation: 965

Rails sets up a lot of convenience so that you can e.g. send mails from the controller easily.

In the console, you are not in the context of a controller, therefore you have not set this up already. The same would go for view-helpers.

In order to use the mail-method, you need to tell Ruby where to look for it.

It should be enough to send the mail like this:

ActionMailer::Base.mail(from: "[email protected]", to: @receiver, subject: @subject, body: "Test").deliver

Keep in mind that you can also use different delivery_methods, if you just want to test the mail-generation, but not yet the integration with your SMTP.

Upvotes: 1

ashvin
ashvin

Reputation: 2040

You can test mail using following way

ActionMailer::Base.mail(from: "[email protected]", to: @receiver, subject: @subject, body: "Test").deliver

Upvotes: 11

Related Questions