minitest icon indicating copy to clipboard operation
minitest copied to clipboard

Fix warning from Forwardable for Mock

Open sovetnik opened this issue 6 years ago • 4 comments

Ruby 2.4 warns when delegating to a private method with Forwardable: https://bugs.ruby-lang.org/projects/ruby-trunk/repository/revisions/56210.

When delegating to a Minitest::Mock object with Forwardable, a "forwarding to private method" warning is shown.

For example, given:

require "forwardable"

class Foo
 extend Forwardable

 attr_reader :baz

 def_delegator :baz, :bar

 def initialize(baz)
   @baz = baz
 end
end

require "minitest/autorun"

class FooTest < Minitest::Spec
 let(:baz) { MiniTest::Mock.new }
 let(:foo) { Foo.new(baz) }

 before do
   baz.expect(:bar, 'foobar')
 end

 it 'produce warnings' do
   expect(foo.bar).must_equal 'foobar'
 end
end

The test will output:

# Running:

warning.rb:26: warning: Foo#bar at warning.rb:8 forwarding to private method Minitest::Mock#bar
.

Finished in 0.000593s, 1686.3410 runs/s, 1686.3410 assertions/s.

1 runs, 1 assertions, 0 failures, 0 errors, 0 skips

Ideally these warnings would not be shown, because in most cases the expectation is set on a public method.

There explained why:

When you define method_missing method, you should define respond_to_missing? method too.

require "forwardable"

class Foo
 extend Forwardable

 attr_reader :baz

 def_delegator :baz, :bar

 def initialize(baz)
   @baz = baz
 end
end

require "minitest/autorun"

class MiniTest::Mock
 def respond_to_missing?(symbol, include_private = false)
   @expected_calls.key? symbol || super
 end
end

class FooTest < Minitest::Spec
 let(:baz) { MiniTest::Mock.new }
 let(:foo) { Foo.new(baz) }

 before do
   baz.expect(:bar, 'foobar')
 end

 it 'produce warnings' do
   expect(foo.bar).must_equal 'foobar'
 end
end

So, if we implement respond_to_missing? as recommended, warning disappered.

sovetnik avatar Feb 07 '19 14:02 sovetnik

Can you convert your example above into a test please?

zenspider avatar Jun 02 '19 21:06 zenspider

Yes, I’ll try

sovetnik avatar Aug 08 '19 15:08 sovetnik

anything?

zenspider avatar Jan 12 '20 00:01 zenspider

In Ruby 2.5 this solution does not seem to get rid of the warning for me

singpolyma avatar May 18 '21 17:05 singpolyma