Home > Software design >  is there a proper way to use is_a? with an instance_double?
is there a proper way to use is_a? with an instance_double?

Time:03-03

I have real world code which does something like:

attr_reader :response
def initialize(response)
  @response = response
end

def success?
  response.is_a?(Net::HTTPOK)
end

and a test:

subject { described_class.new(response) }
let(:response) { instance_double(Net::HTTPOK, :body => 'nice body!', :code => 200) }

it 'should be successful' do
  expect(subject).to be_success
end

This fails because #<InstanceDouble(Net::HTTPOK) (anonymous)> is not a Net::HTTPOK

... The only way I have been able to figure out how to get around this is with quite the hack attack:

let(:response) do
  instance_double(Net::HTTPOK, :body => 'nice body!', :code => 200).tap do |dbl|
    class << dbl
      def is_a?(arg)
        instance_variable_get('@doubled_module').send(:object) == arg
      end
    end
  end
end

I can't imagine that I am the only one in the history ruby and rspec that is testing code being that performs introspection on a test double, and therefore think there has got to be a better way to do this-- There has to be a way that is_a? just will work out the box with a double?

CodePudding user response:

I would do:

let(:response) { instance_double(Net::HTTPOK, :body => 'nice body!', :code => 200) }
before { allow(response).to receive(:is_a?).with(Net::HTTPOK).and_return(true) }
  • Related