[RUBY] Check method call arguments in blocks with RSpec

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

Check method call arguments in blocks with RSpec
Call your own method with PreAuthorize in Spring Security
Check CSV value with RSpec
Integer check method with ruby
[ruby] Method call with argument
Use constructor with arguments in cucumber-picocontainer
Call the super method in Java
Overload method with Int and Integer arguments
Call Java method from JavaScript executed in Java
Concurrency Method in Java with basic example
Java method call from RPG (method call in own class)
About call timing and arguments of addToBackStack method
About characters that are completed in method arguments
How to call functions in bulk with Java reflection
Include image in jar file with java static method
Call a method with a Kotlin callback block from Java
I got an error "undefined method` create'" in RSpec
Check coverage with Codecov in Java + Gradle + Wercker configuration