简体   繁体   English

如何使用devise,rspec,capybara和mailspec测试dev邮件传递

[英]How to test devise mail delivery with devise, rspec, capybara, and mailspec

I'm trying to test if devise is sending out confirmation emails. 我正在尝试测试设计是否正在发送确认电子邮件。 This is becomming to be a bit of a challenge to me because, the tests use a different environment in Rails and I'm not quite sure if I'm going the right route. 这对我来说是个挑战,因为测试在Rails中使用了不同的环境,而且我不确定是否要选择正确的路线。 Here's my rspec test. 这是我的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

This is the message when I run the spec. 这是我运行规范时的消息。

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

I would like to test this feature, but can Rails send out emails in a test environment? 我想测试此功能,但是Rails可以在测试环境中发送电子邮件吗? If so what kind of code makes this type of code pass? 如果是这样,哪种类型的代码可以通过? I have the mailer set up to sendgrid, so I can show that as well. 我已经将邮件程序设置为sendgrid,所以我也可以显示出来。 User's of Devise are set to confirmable, so a confirmation email is supposed to be coming out. “ Devise用户”设置为“可确认”,因此应该发送确认电子邮件。

Make sure you have this set in your you have this set in config/environments/test.rb : 确保已在config/environments/test.rb设置了此设置:

config.action_mailer.delivery_method = :test

In your spec, you can also just test that ActionMailer::Base.deliveries has changed: 在您的规范中,您还可以仅测试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

Similarly, if you're using Sidekiq, you can instead check that the number of Sidekiq jobs went up. 同样,如果您使用的是Sidekiq,则可以检查一下Sidekiq作业的数量是否增加。

Personally, I'd save testing the specifics of the email for a unit test, and use the feature test to make sure that everything's wired together. 就个人而言,我将保存电子邮件的详细信息以进行单元测试,并使用功能测试来确保所有内容都连接在一起。

Also, if you want to verify manually that the emails are getting sent, Mailcatcher is pretty nice. 另外,如果您想手动验证是否正在发送电子邮件, Mailcatcher非常不错。

You could try to write in test environment: 您可以尝试在测试环境中编写:

config.action_mailer.perform_deliveries = true 

I hope it will help You! 希望对您有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM