【问题标题】:How to test devise mail delivery with devise, rspec, capybara, and mailspec如何使用 devise、rspec、capybara 和 mailspec 测试设计邮件传递
【发布时间】:2015-04-12 16:46:07
【问题描述】:

我正在尝试测试 devise 是否正在发送确认电子邮件。这对我来说变得有点挑战,因为测试在 Rails 中使用了不同的环境,我不太确定我是否走对了路。 这是我的 rspec 测试。

describe "Sign up:", :type => :feature do

  before(:each) do
    @user = FactoryGirl.build(:user)

    visit root_path

    click_link "Sign Up"

    fill_in "Name", :with => @user.name
    fill_in "Email", :with => @user.email
    fill_in "Password", :with => @user.password
    fill_in "Password confirmation", :with => @user.password

    click_button "Sign up"
end

describe "user gets a confirmation email" do
 subject { ActionMailer::Base.deliveries.last }
 it { is_expected.to deliver_to(@user.email) }
end

这是我运行规范时的消息。

 Failure/Error: it { is_expected.to deliver_to(@user.email) }
 NoMethodError:
   undefined method `perform_deliveries' for nil:NilClass

我想测试这个功能,但是 Rails 可以在测试环境中发送电子邮件吗?如果是这样,什么样的代码使这种类型的代码通过?我将邮件程序设置为 sendgrid,所以我也可以显示它。 Devise 的用户设置为可确认,因此应该会发送一封确认电子邮件。

【问题讨论】:

  • 问题可能是您的邮件程序正在异步交付,并且交付实际上是在您的预期之后执行的。 IE。 sleep 1 在您的期望可能会解决您的问题之前(尽管这被广泛认为是一种反模式)

标签: ruby-on-rails devise capybara mailer


【解决方案1】:

确保你有这个集合你有这个集合在config/environments/test.rb:

config.action_mailer.delivery_method = :test

在您的规范中,您也可以只测试 ActionMailer::Base.deliveries 是否已更改:

describe "Sign up:", :type => :feature do
  # ...

  it "sends a confirmation email" do
    expect {
      click_button "Sign up"

      # for example. the point is to wait for the AJAX response
      page.find('p.thanks', text: 'Thanks for signing up')
    }.to change { ActionMailer::Base.deliveries.size }.by(1)
  end
end

同样,如果您使用的是 Sidekiq,则可以改为检查 Sidekiq 作业的数量是否增加。

就我个人而言,我会将测试电子邮件的细节用于单元测试,并使用功能测试来确保所有内容都连接在一起。

另外,如果您想手动验证电子邮件是否已发送,Mailcatcher 非常好。

【讨论】:

    【解决方案2】:

    您可以尝试在测试环境中编写:

    config.action_mailer.perform_deliveries = true 
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2013-05-30
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 2017-04-10
      相关资源
      最近更新 更多