RSpec 不满足条件时如何测试,测试验证方法

问题描述 投票:0回答:1

“当客户关闭通知时,

notify_on
变为假,并且不满足某些条件。我正在考虑的方法是检查当
BellNotify.create!
为真时是否执行
notify_on

如果这种方法正确,请告知如何编写代码。我尝试过以下方法:


RSpec.describe NotificationSetting, type: :model do
  describe '#create_notify' do
    context 'when notify_on is true' do
      it 'executes BellNotify.create!' do
        # Set up a notification setting where notify_on is true
        setting = NotificationSetting.new(notify_on: true)
        
        # Allow BellNotify.create! to be called
        allow(BellNotify).to receive(:create!)
        
        # Trigger the method that should call BellNotify.create!
        setting.send(:create_notify)
        
        # Check that BellNotify.create! has been received
        expect(BellNotify).to have_received(:create!)
      end
    end
  end
end

如果有其他测试方法请告诉我

我尝试验证在不满足特定条件时是否执行某个类的方法。

ruby-on-rails rspec rspec-rails
1个回答
0
投票

我认为这种方法是正确的,我只是做一些调整以避免重复几行。

RSpec.describe NotificationSetting, type: :model do
  describe '#create_notify' do
  let(:notify_on) { true }
  let(:settings) { NotificationSetting.new(notify_on: notify_on) }
  
  before { allow(BellNotify).to receive(:create!) }

  context 'when notify_on is true' do
    it 'executes BellNotify.create!' do
      setting.send(:create_notify)
      expect(BellNotify).to have_received(:create!)
    end
  end

  context 'when notify_on is false' do
    let(:notify_on) { false }

    it 'does not execute BellNotify.create!' do
      setting.send(:create_notify)
      expect(BellNotify).not_to have_received(:create!)
    end
  end
end

© www.soinside.com 2019 - 2024. All rights reserved.