Method: Mocha::Expectation#with
- Defined in:
- lib/mocha/expectation.rb
#with(*expected_parameters_or_matchers) {|actual_parameters| ... } ⇒ Expectation
Modifies expectation so that the expected method must be called with expected_parameters_or_matchers.
May be used with Ruby literals or variables for exact matching or with parameter matchers for less-specific matching, e.g. ParameterMatchers::Methods#includes, ParameterMatchers::Methods#has_key, etc. See ParameterMatchers for a list of all available parameter matchers.
Alternatively a block argument can be passed to #with to implement custom parameter matching. The block receives the *actual_parameters as its arguments and should return true if they are acceptable or false otherwise. See the example below where a method is expected to be called with a value divisible by 4. The block argument takes precedence over expected_parameters_or_matchers. The block may be called multiple times per invocation of the expected method and so it should be idempotent.
Note that if #with is called multiple times on the same expectation, the last call takes precedence; other calls are ignored.
Positional arguments were separated from keyword arguments in Ruby v3 (see this article). In relation to this a new configuration option (Configuration#strict_keyword_argument_matching=) is available in Ruby >= 2.7.
When Configuration#strict_keyword_argument_matching= is set to false (which is the default in Ruby v2.7), a positional Hash and a set of keyword arguments passed to #with are treated the same for the purposes of parameter matching. However, a deprecation warning will be displayed if a positional Hash matches a set of keyword arguments or vice versa.
When Configuration#strict_keyword_argument_matching= is set to true (which is the default in Ruby >= v3.0), an actual positional Hash will not match an expected set of keyword arguments; and vice versa, an actual set of keyword arguments will not match an expected positional Hash, i.e. the parameter matching is stricter.
324 325 326 327 |
# File 'lib/mocha/expectation.rb', line 324 def with(*expected_parameters_or_matchers, &matching_block) @parameters_matcher = ParametersMatcher.new(expected_parameters_or_matchers, self, &matching_block) self end |