I'm running into a runtime TypeError from Sorbet when mocking a class constructor with as_stubbed_const, even though RSpec::Sorbet.allow_doubles! is enabled.
Problem
I'm testing a method that returns an instance of a class (Thing). In the spec, I:
- Stub
Thing.new to return an thing_instance = instance_double(Thing)
- Use
class_double(Thing, new: thing_instance).as_stubbed_const
- Enable
RSpec::Sorbet.allow_doubles!
Despite that, Sorbet raises this error:
TypeError:
Return value: Expected type Thing,
got type RSpec::Mocks::InstanceVerifyingDouble with value #<InstanceDouble(Thing)>
However, if I remove class_double(Thing, new: thing_instance).as_stubbed_const and just do:
allow(Thing).to receive(:new).and_return(thing_instance)
…it works fine and Sorbet doesn’t complain.
Minimal Repro
# typed: true
class Thing
extend T::Sig
sig { params(name: String).void }
def initialize(name:); end
end
class Widget
extend T::Sig
sig { params(name: String).returns(Thing) }
def build(name)
Thing.new(name: name)
end
end
# spec/models/widget_spec.rb
require "rails_helper"
RSpec::Sorbet.allow_doubles!
RSpec.describe Widget do
let(:thing_instance) { instance_double(Thing) }
before do
class_double(Thing, new: thing_instance).as_stubbed_const
end
it "returns a Thing" do
result = Widget.new.build("hello")
expect(result).to eq(thing_instance)
end
end
Question
Is it expected that class_double(...).as_stubbed_const causes Sorbet to raise a type error when the class under test returns an instance_double of that class?
Calling allow(MyClass).to receive(:new).and_return(my_instance_double) works fine without as_stubbed_const, but adding as_stubbed_const leads to Sorbet rejecting the return value, even when RSpec::Sorbet.allow_doubles! is used.
Is this a known issue, or is there a recommended way to configure rspec-sorbet to allow this?
Thanks!
I'm running into a runtime
TypeErrorfrom Sorbet when mocking a class constructor withas_stubbed_const, even thoughRSpec::Sorbet.allow_doubles!is enabled.Problem
I'm testing a method that returns an instance of a class (
Thing). In the spec, I:Thing.newto return anthing_instance = instance_double(Thing)class_double(Thing, new: thing_instance).as_stubbed_constRSpec::Sorbet.allow_doubles!Despite that, Sorbet raises this error:
However, if I remove
class_double(Thing, new: thing_instance).as_stubbed_constand just do:…it works fine and Sorbet doesn’t complain.
Minimal Repro
Question
Is it expected that
class_double(...).as_stubbed_constcauses Sorbet to raise a type error when the class under test returns aninstance_doubleof that class?Calling
allow(MyClass).to receive(:new).and_return(my_instance_double)works fine withoutas_stubbed_const, but addingas_stubbed_constleads to Sorbet rejecting the return value, even whenRSpec::Sorbet.allow_doubles!is used.Is this a known issue, or is there a recommended way to configure rspec-sorbet to allow this?
Thanks!