RSpec 使用条件测试销毁操作

RSpec testing a destroy action with a conditional

我正在尝试测试一个有条件的销毁操作,如果我只是在没有参数的情况下调用业务,它就可以正常工作:

def destroy
    if @message_rule.destroy
      Messages::Reclassifier.call
    end

但如果我那样做:

def destroy
    if @message_rule.destroy
      Messages::Reclassifier.call(allowed_params[:message])
    end

它 returns 我这个错误:

Failures:

  1) MessageRulesController#destroy When the message_rule has been destroyed classifies the messages
     Failure/Error: expect(Messages::Reclassifier).to have_received(:call)

       (Messages::Reclassifier (class)).call(*(any args))
           expected: 1 time with any arguments
           received: 0 times with any arguments
     # ./spec/controllers/message_rules_controller_spec.rb:108:in `block (4 levels) in <top (required)>'

这是规范:

describe '#destroy' do
    let(:message_rule) { build_stubbed(:message_rule) }

    before do
      allow(Messages::Reclassifier).to receive(:call)

      allow(MessageRule).to receive(:find).
        with(message_rule.id.to_s).
        and_return(message_rule)
    end

    subject(:destroy) { delete :destroy, params: { id: message_rule.id } }

    context 'When the message_rule has been destroyed' do
      before { allow(message_rule).to receive(:destroy).and_return(true) }

      it 'classifies the messages' do
        destroy

        expect(Messages::Reclassifier).to have_received(:call)
      end
    end

    context 'When the message_rule couldn\'t be destroyed' do
      before { allow(message_rule).to receive(:destroy).and_return(false) }

      it 'does not reclassify the messages' do
        destroy

        expect(Messages::Reclassifier).not_to have_received(:call)
      end
    end
  end

我在规范中做错了什么吗?我对 RSpec 没有经验,所以我很难理解这个错误

错误表明 Rspec 预期 Messages::Reclassifier 调用方法 call,但未调用该方法。这意味着某些东西阻止了方法调用的发生。您似乎已正确设置方法存根。

由于您在没有参数选项的情况下对 Messages::Reclassifier#call 进行存根,因此 Rspec 您是否将参数传递给 Messages::Reclassifier#call 应该无关紧要。但是,如果 allowed_params[:message] 参数导致类似异常的情况,那将很重要。

您能否提供整个控制器 class 或至少与 "destroy" 操作相关的所有代码?