rspec / rspec

The RSpec monorepo
MIT License
8 stars 0 forks source link

Stubbing private kernel methods like `rand` or `sleep` on a partial double that subclasses `DelegateClass` issues warning #42

Open myronmarston opened 10 years ago

myronmarston commented 10 years ago
require 'delegate'

class DelegatedHash < DelegateClass(Hash)
  def do_something_random
    if rand(2) == 1
      puts "jackpot"
    end
  end
end

describe DelegatedHash do
  it 'can stub `rand`' do
    hash = DelegatedHash.new({})
    allow(hash).to receive(:rand).and_return(0)
    hash.do_something_random
  end
end

Produces a warning:

/Users/myron/code/rspec-dev/repos/rspec-support/lib/rspec/support.rb:45:in `method': delegator does not forward private method #rand

As always, stubbing private methods is a bad idea, but this is a confusing warning for users to get. The fix may be in rspec support.

fables-tales commented 10 years ago

I understood everything in this issue description apart from: The fix may be in rspec support.. As far as I'm aware there's not code in RSpec support to deal with this. Do you mean that a fix should end up in RSpec support, or that RSpec should start supporting users doing this with its own warning?

myronmarston commented 10 years ago

I understood everything in this issue description apart from: The fix may be in rspec support.. As far as I'm aware there's not code in RSpec support to deal with this. Do you mean that a fix should end up in RSpec support, or that RSpec should start supporting users doing this with its own warning?

The warning is being generated from this line of code in rspec-support, so I meant that the fix for this may be in that method. Or it may be here in rspec-mocks. I'm not sure of the best route yet.

fables-tales commented 10 years ago

A proposed solution for this was written in https://github.com/rspec/rspec-support/pull/63. We decided it'd be better to simply silence warnings in the RSpec support method, and unsilence them once that's done.