RSpec's ʻexpect (foo) .to receive (: bar) .with (...) `checks arguments [in several ways](https://relishapp.com/rspec/rspec-mocks/ v / 3-9 / docs / setting-constraints / matching-arguments), but there are quite a few cases where you want to verify with blocks.
You can pass a matcher to with, so you can define a custom matcher. In the example below, only a specific attribute of Struct is verified.
RSpec::Matchers.define :a_valid_argument do
match {|actual| block_arg.call(actual) }
end
it "should call with valid argument" do
jon = Struct.new(:name).new("Jon")
expect($stdout).to receive(:write).with(
a_valid_argument {|a| a.name == "Jon" },
)
$stdout.write(jon)
end
Note that argument verification by with
is performed for each argument, so in the case of a method that takes multiple arguments, it is necessary to pass matcher for each argument.
it "should call with valid arguments" do
jon = Struct.new(:name).new("Jon")
dany = Struct.new(:name).new("Dany")
expect($stdout).to receive(:write).with(
a_valid_argument {|a| a.name == "Jon" },
a_valid_argument {|a| a.name == "Dany" },
)
$stdout.write(jon, dany)
end
Recommended Posts