【问题标题】:RSpec how to mock controller method inside concern?RSpec如何在关注中模拟控制器方法?
【发布时间】:2018-02-26 14:29:14
【问题描述】:

我有以下几点:

class PaymentController < ActionController::API
  include ObjectActions

  def error_notification(message)
    puts "An error has occurred: #{message}"
  end
end

module ObjectActions
  extend ActiveSupport::Concern

  def process
    if valid?
      # process payment
    else
      error_notification("Payment is not valid")
    end
  end
end

现在,我正在尝试在 ObjectActions 模块/关注中模拟/存根“外部”error_notification 方法。

RSpec.describe ObjectActions, type: :concern do
  include ObjectActions

  before do
    allow(described_class).to receive(:valid?).and_return(false)

    # I KNOW THIS IS NOT RIGHT, HOW CAN I PROPERLY MOCK IT?
    allow(described_class).to receive(:error_notification).and_return("Blah blah")
  end

  context '#process' do
    it { expect { process }.to eq("Blah blah") }
  end
end

【问题讨论】:

  • 所以你知道你做的完全错了,还想继续做吗?有什么意义?
  • 这是什么type: :concern?我以前从未见过它,也没有在官方 rspec 文档中看到它。
  • @nattfodd 逻辑没有错,我只是想找出模拟这种情况的方法
  • @meta 这样我“标记”了我的关注规范并在 rails_helper.rb 中应用了一些配置
  • 你也可以分享这个代码(rails_helper.rb)吗?

标签: ruby-on-rails rspec mocking rspec-rails


【解决方案1】:

简短的回答是

allow(self).to receive(:error_notification).and_return("Blah blah")

为什么?

你正在包含模块,你想在当前测试中测试

RSpec.describe ObjectActions, type: :concern do
  include ObjectActions

所以这就是你应该模拟的。但这是一种更好的方法,我不久前在这个答案中描述了这一点:https://stackoverflow.com/a/48914463/299774

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多