RSpec不允许嵌套参数与哈希参数匹配



我正在尝试使用RSpec的参数匹配功能,以确保使用正确的哈希参数调用方法。不幸的是,RSpec似乎不允许我说receive(:foo).with(instance_of(MyClass) => :bar, instance_of(MyClass) => :baz)之类的话,大概是因为这个参数是一个散列。

我尝试使用including_hash匹配器来表示receive(:foo).with(hash_including(instance_of(MyClass) => :bar, instance_of(MyClass) => :baz)),但这也不起作用。

以下是问题的再现:

#!/usr/bin/env ruby
require "rspec"
class Account
def initialize(logger)
@logger = logger
end
def open_with_hash_arg
pipe_r, pipe_w = IO.pipe
@logger.account_opened(pipe_r => :read, pipe_w => :write)
end
def open_with_flat_args
pipe_r, pipe_w = IO.pipe
@logger.account_opened(pipe_r, pipe_w)
end
end
describe Account do
it "fails with hash arg" do
logger = double("Logger")
expect(logger).to receive(:account_opened).with(instance_of(IO) => :read, instance_of(IO) => :write)
account = Account.new(logger)
account.open_with_hash_arg
end
it "succeeds with flat args" do
logger = double("Logger")
expect(logger).to receive(:account_opened).with(instance_of(IO), instance_of(IO))
account = Account.new(logger)
account.open_with_flat_args
end
end

这是这个程序的输出:

$ rspec ./tmp.rb
F.
Failures:
1) Account fails with hash arg
Failure/Error: @logger.account_opened(pipe_r => :read, pipe_w => :write)

#<Double "Logger"> received :account_opened with unexpected arguments
expected: ({an_instance_of(IO)=>:read, an_instance_of(IO)=>:write})
got: ({#<IO:fd 5>=>:read, #<IO:fd 6>=>:write})
Diff:
@@ -1 +1 @@
-[{an_instance_of(IO)=>:read, an_instance_of(IO)=>:write}]
+[{#<IO:fd 5>=>:read, #<IO:fd 6>=>:write}]

# ./tmp.rb:12:in `open_with_hash_arg'
# ./tmp.rb:26:in `block (2 levels) in <top (required)>'
Finished in 0.01154 seconds (files took 0.04986 seconds to load)
2 examples, 1 failure
Failed examples:
rspec ./tmp.rb:22 # Account fails with hash arg

如何使用RSpec测试是否使用哈希参数调用方法,其中键是某个类的实例?

请注意,我使用的是RSpec 3.11版

您的方法调用很奇怪,我本来以为它是@logger.account_opened(:read => pipe_r, :write => pipe_w),所以哈希键是符号,值是IO对象。如果是这样的话,你可以用下面的方法来测试它

expect(logger).to receive(:account_opened).with(:read => instance_of(IO), :write => instance_of(IO))

最新更新