Call when_declaring_verifying_double for any_instance partial mocks
Created by: dorner
Using allow_ or expect_any_instance_of does not call the when_declaring_verifying_double callbacks
See https://github.com/rspec/rspec-rails/issues/1357.
The when_declaring_verifying_double callbacks only get called when instance_double and its ilk are called. In the case of any_instance, these callbacks are never called. The ramification of this is that rspec-rails will fail to dynamically define methods in this case and rspec-mocks will claim that the method doesn't exist.
Your environment
- Ruby version: 2.6
- rspec-mocks version: 3.10.0-pre
Steps to reproduce
Set verify_partial_mocks to true, then use allow_any_instance_of
or expect_any_instance_of
with a class that uses the callback to define dynamic methods.
# frozen_string_literal: true
begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
raise e
end
gemfile(true) do
source "https://rubygems.org"
gem "rspec", "3.7.0" # Activate the gem and version you are reporting the issue against.
end
puts "Ruby version is: #{RUBY_VERSION}"
require 'rspec/autorun'
class MyClass
def self.define_attribute_methods!
unless method_defined?(:some_method_defined_dynamically)
define_method(:some_method_defined_dynamically) { true }
end
end
end
RSpec.configuration.mock_with(:rspec) do |config|
config.verify_partial_doubles = true
config.when_declaring_verifying_double do |reference|
reference.target.define_attribute_methods! if reference.target.is_a?(Class)
end
end
RSpec.describe 'dynamic methods' do
expect_any_instance_of(MyClass).to receive(:some_method_defined_dynamically)
end
Expected behavior
The callback should be called and the method should exist.
Actual behavior
The callback is not called and the method does not exist and raises an error.