gpt4 book ai didi

ruby - 如何使用 rspec 测试 DSL API 方法

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:51 24 4
gpt4 key购买 nike

我想测试一个方法是否接收到一个 block ...但是我的 rspec stub 返回 (no args)

这是一个人为的例子......

class Foo
def self.bar &block
end
end

describe Foo do
before do
Foo.stub(:bar)
Foo.bar { 'foo'}
end
it 'should' do
expect(Foo).to have_received(:bar).with(kind_of(Proc))
end
end

结果...

  1) Foo should
Failure/Error: expect(Foo).to have_received(:bar).with(kind_of(Proc))
<Foo (class)> received :bar with unexpected arguments
expected: (#<RSpec::Mocks::ArgumentMatchers::KindOf:0x1022a7b20 @klass=Proc>)
got: (no args)

编辑

这里是一个不太无意义的例子,其中实现了 Peter 的解决方案......

foo.rb

class Foo
def self.setup &block
@setup ||= block
end
def setup
instance_eval &self.class.setup
end
end

bar.rb

# DSL designed class
class Bar < Foo
setup do
# setup Bar instances here
end
end

bar_spec.rb

# Need to make sure DSL classes are correctly implemented
describe Bar do
after do
load 'bar'
end

it 'should define .setup' do
expect(Bar).to receive(:setup){ |&block| expect(block).to be_a(Proc) }
end
end

最佳答案

我认为没有任何方法可以在事后验证 block 是否已通过,但如果您使用正常的执行前预期,则可以按如下方式检查它:

class Foo
def self.bar &block
puts 'DO NOT RUN'
end
end

describe 'Foo#bar' do
it 'should confirm a block is passed' do
expect(Foo).to receive(:bar) {|&block| expect(block).to be_a(Proc)}
Foo.bar {}
end
it 'should confirm a block is not passed' do
expect(Foo).to receive(:bar) {|&block| expect(block).to be_nil}
Foo.bar
end
end

如果您不介意实际屈服于该 block ,则可以使用 .and_yield,如果 block 不存在,这将产生预期错误。

class Foo
def self.bar &block
end
end

describe Foo do
before do
Foo.stub(:bar), y
end
it 'should' do
expect(Foo).to receive(:bar).and_yield
Foo.bar {}
end
end

关于ruby - 如何使用 rspec 测试 DSL API 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20895495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com