1

我有“控制器/users_controller.rb”

def create
   user = User.new(person_params)
   if user.save
     EmailSendJob.perform_later(user.email, 'random_password')
   end
 end

我有'mailers/user_mailer.rb'

def user_new(user_to, password)
  @password = password
  mail to: user_to, subject: "Password for you"
end

我有“工作/email_send_job.rb”

def perform(email, password)
  UserMailer.user_new(email, password).deliver_now
end

我该如何进行测试?谢谢

我看到了“电子邮件规范”,但我的代码无法理解

我有'spec/controllers/users_controller_spec.rb'

require "spec_helper"
require "rails_helper"
require "email_spec"

describe UsersController do   
  User.delete_all

  before(:all) do
    @email_for_test = "222@222@mail.ru"

    @user = User.new
    @user.email = "2@2.ru"
    @user.name = "test"
    @user.save
  end


  it "create" do
    post :create, params: {user: {email: @email_for_test,
                                  name:"test",
                                  description: "test"}}
    user = User.last
    expect(user.email).to eq(@email_for_test)

    last_delivery = ActionMailer::Base.deliveries.last
    last_delivery.body.raw_source.should include "This is the text of the email"

  end

end

ActionMailer::Base.deliveries.last 不起作用
也许你有例子。我会很感激

4

3 回答 3

0

尝试使用ActionMailer::Base.deliveries.count

例如:

  it "sends an email" do
    expect { UserMailer.user_new(email, password).deliver }.to change { ActionMailer::Base.deliveries.count }.by(1)
  end
于 2017-03-15T18:25:06.080 回答
0

我倾向于在功能规范中使用电子邮件规范。测试将如下所示:

require 'rails_helper'

feature 'Admin creates purchase' do
  include ActionView::Helpers::NumberHelper

  given(:purchase)     { build(:purchase) }
  given(:new_purchase) { Purchase.last }

  scenario 'with valid input' do
    click_link 'Purchases'
    click_link 'New Purchase'
    fill_in 'Name', with: purchase.name
    fill_in 'Email', with: purchase.email
    fill_in 'Quantity', with: purchase.quantity

    perform_enqueued_jobs do
      click_button 'Create Purchase'
      expect(page).to have_content 'The purchase was completed successfully'

      open_email(purchase.email)
      expect(current_email).to have_subject 'Receipt from My Super Awesome Company'
      expect(current_email).to have_content "Name #{purchase.name}"
      expect(current_email).to have_content "Total Charge #{number_to_currency(new_purchase.total)}"
    end
  end
end

您可能可以在控制器规范中进行类似的内容检查。

于 2017-03-15T18:34:23.253 回答
0

好的,我认为答案很好..我还发现了一些东西-

    it "sends an email" do
      email = UserMailer.password_new(@email_for_test,   "password_test").deliver
      m = ActionMailer::Base.deliveries
      expect(m.count).to eq(1)
      expect(email.html_part.body).to include("Hello, your new password")
    end

email = ActionMailer::Base.deliveries.last
(email.text_part || email.html_part || email).body
于 2017-03-15T20:08:59.547 回答