rspec email_spec和jobs ..它是如何工作的?我想检查信件是否已发送..也许是电子邮件正文

时间:2017-03-15 16:49:55

标签: ruby-on-rails testing rspec jobs email-spec

我有'controllers / 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

我有'jobs / email_send_job.rb'

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

我该如何进行测试?谢谢

我看到'email-spec',但无法理解我的代码

我有'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不起作用 也许你有榜样。我将非常感激

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

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

答案 2 :(得分: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