如何在关注中模拟一个方法?
How to mock a method inside concern?
我有 FooConcern
和 BarService
如下:
module FooConcern
extend ActiveSupport::Concern
def notify_slack(message)
# send message to slack
end
end
class BarService
include FooConcern
def run
# do some stuff
message = 'blah, blah'
notify_slack(message)
end
end
我如何编写模拟 notify_slack
,这样当我 运行 Rspec 测试 BarService#run
时我实际上不会调用 slack API?
RSpec.describe BarService do
describe 'run' do
subject { described_class.new.run }
it do
# some tests on things other than notifying slack
end
end
end
您可以使用 allow 模拟该方法。
RSpec.describe BarService do
describe 'run' do
subject { described_class.new }
it do
allow(subject).to receive(:notify_slack).and_return(true)
# some tests on things other than notifying slack
subject.run
end
end
end
我有 FooConcern
和 BarService
如下:
module FooConcern
extend ActiveSupport::Concern
def notify_slack(message)
# send message to slack
end
end
class BarService
include FooConcern
def run
# do some stuff
message = 'blah, blah'
notify_slack(message)
end
end
我如何编写模拟 notify_slack
,这样当我 运行 Rspec 测试 BarService#run
时我实际上不会调用 slack API?
RSpec.describe BarService do
describe 'run' do
subject { described_class.new.run }
it do
# some tests on things other than notifying slack
end
end
end
您可以使用 allow 模拟该方法。
RSpec.describe BarService do
describe 'run' do
subject { described_class.new }
it do
allow(subject).to receive(:notify_slack).and_return(true)
# some tests on things other than notifying slack
subject.run
end
end
end