binarymason binarymason - 3 months ago 21
Ruby Question

Correct way to double a class instance with RSpec?

I'm trying to make a test double for a class instance with RSpec. Say I have a test that only accepts a File object as an argument.

Great, now how do I make a double so I don't have to pass in an actual file with all of my specs?

let(:file) { double(File) }
raise "NOT A FILE" unless file.is_a? File
# => RuntimeError: NOT A FILE


I've also tried this:

let(:file) { instance_double(File) }
raise "NOT A FILE" unless file.is_a? File
# => RuntimeError: NOT A FILE


And this (which is expecting an actual file):

let(:file) { object_double(File.new) }
# => ArgumentError: wrong number of arguments


What am I doing wrong?

Answer

You can just stub the is_a? call.

file = instance_double(File)
allow(file).to receive(:is_a?).with(File).and_return(true)