我试图使用RSpec的参数匹配特性来确保方法被正确的hash参数调用。不幸的是,RSpec似乎不允许我说receive(:foo).with(instance_of(MyClass) => :bar, instance_of(MyClass) => :baz)
之类的话,大概是因为参数是一个hash。
我尝试使用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版
1条答案
按热度按时间gzjq41n41#
你的方法调用很奇怪,我希望它是
@logger.account_opened(:read => pipe_r, :write => pipe_w)
,所以哈希键是符号,值是IO对象。如果是这样的话,你可以用下面的代码来测试它。