我有一个方法,它有一个sorbet类型的签名定义。当尝试在使用RSpec的测试中模拟此方法时,我得到了一个类型不匹配错误。我正在尝试理解如何解决这个问题,并且可以在不影响冰沙类型检查的情况下添加基于RSpec的测试。
sig {params(login_context: LoginContext, company_id: String).returns(T::Boolean)}
def populate_dummy_data(login_context, company_id)
测试代码:
@login_context = double(LoginContext, :requester => @requester) # Creates an instance of type Rspec::Mocks::double
错误:
expected no Exception, got #<TypeError: Parameter ‘login_context’: Expected type LoginContext, got type RSpec::Mocks::Double wit...a_populator_spec.rb:42
发布于 2019-07-05 22:46:59
解决方案1:
使用带有适当类的instance_double
,并模拟它的is_a?
。要在全局范围内完成此操作,请执行monkey patching:
require 'rspec/mocks'
class RSpec::Mocks::InstanceVerifyingDouble
def is_a?(expected)
@doubled_module.target <= expected || super
end
end
解决方案2:
有选择地,当mock导致时,不要引发异常。这样,除非使用mock,否则Sorbet仍然会执行类型检查。
require 'sorbet-runtime'
RSpec.configure do |config|
config.before :each, sorbet: :mocks do
T::Configuration.inline_type_error_handler = proc do |error|
raise error unless error.message.include? "got type RSpec::Mocks"
end
T::Configuration.call_validation_error_handler = proc do |_signature, opts|
raise TypeError.new(opts[:pretty_message]) unless opts[:message].include? "got type RSpec::Mocks"
end
end
config.after :each, sorbet: :mocks do
T::Configuration.inline_type_error_handler = nil
T::Configuration.call_validation_error_handler = nil
end
end
https://stackoverflow.com/questions/56742572
复制相似问题