Rspec 使用助手中的参数从控制器测试邮件程序

Rspec test mailer from controller with params in helper

我遇到了一个相当奇怪的 rspec 失败,感觉 像是测试配置问题或 rspec 或 rspec 中的错误-rails(rspec 3.4.0 和 rspec-rails 3.4.2)。我希望就此事提出任何建议:

我有一个控制器测试,它只调用一个邮件程序方法,该方法的模板使用该帮助器,我从使用参数的帮助器函数中得到一个错误。

describe MyController, :type => :controller do
  describe "POST send_a_specific_type_of_email" do
    it "sends the fact sheet" do
      ActionMailer::Base.deliveries = []
     post :send_a_specific_type_of_email, params
     expect(ActionMailer::Base.deliveries.count).to eq(1)
    end
  end
end

这会导致错误,该错误与我使用参数的辅助方法有关。

Failure/Error: if params[:some_value] == "on"

ActionView::Template::Error:
 undefined method `params' for #<MyMailer:0x007fdcf56020f0>
# ./app/helpers/mycontroller_helper.rb:139:in `display_mycontroller_price'
# ./app/views/mycontroller/_items.html.erb:26:in `_app_views_mycontroller__items_html_erb__2241527061928464634_70293475039080'
# ./app/views/production_mailer/email_mycontroller.html.erb:17:in `_app_views_production_mailer_email_mycontroller_html_erb___301577404429349505_70293454886780'
# ./app/models/production_mailer.rb:51:in `email_mycontroller'
# ./app/controllers/mycontroller_controller.rb:40:in `send_a_specific_type_of_email'
# ./lib/authenticated_system.rb:75:in `catch_unauthorized'
# ./spec/controllers/mycontroller_controller_spec.rb:109:in `block (4 levels) in <top (required)>'
# ------------------
# --- Caused by: ---
# NoMethodError:
#   undefined method `params' for #<MyMailer:0x007fdcf56020f0>
#   ./app/helpers/mycontroller_helper.rb:139:in `display_mycontroller_price'

如果调用邮件程序方法或帮助程序方法,我尝试将对帮助程序和邮件程序的期望设置为 return nil,但它们从未解决该错误。我既困惑又惊讶地发现邮件程序或帮助程序方法没有任何作用。

这是我尝试存根的方法:

# does nothing
expect(MyHelper).to receive(:display_mycontroller_price).and_return(nil)

# does cover up the issue but causes the above test to fail because 
# deliver_now quantities are no longer being checked, thus negating the purpose of the test in the first place
expect(FactSheetHelper).to receive(:display_factsheet_price).with(project.data).and_return(0)
expect(ProductionMailer).to receive(:params).and_return(params)
expect(message_delivery).to receive(:deliver_now)

我如何才能成功地从控制器规范测试中存根该 Helper 方法,或者这是 rspec 某处的错误?

错误说明了一切,您不能在 Mailer 内部(或通过 Helper 在 Mailer 的上下文中)使用 params。重构,因此您将值作为参数传递给邮件程序方法。