Skip to content

as_stubbed_const causes Sorbet type error when stubbing .new with instance_double despite RSpec::Sorbet.allow_doubles! #31

Description

@baka-san

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!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions