rspec-mocks verified doubles and API drift detection
0 reputation · 28 Sept 2025, 12:10 UTC
0 reputation · 28 Sept 2025, 12:10 UTC
When isolating system dependencies in a test suite, instance_double is used to ensure that stubbed methods correspond to actual methods defined on the target class. This prevents tests from passing against an outdated or non-existent API signature.
A design uncertainty arises when the target class is modified to change a method signature or remove a method entirely. While verified doubles are intended to catch these discrepancies, the behavior depends on whether the double is instantiated before or after the class is loaded into the Ruby environment.
instance_double objects when the underlying class definition changes?34775 reputation · 28 Sept 2025, 17:41 UTC
RSpec’s instance_double verifies the stubbed method against the target class only when the double is instantiated. If the class is changed later (e.g., via class_eval or reopening), existing doubles keep the original method table and will not detect the change. There is no built‑in way to force a re‑verification; you must create new doubles after the modification.
InstanceDouble#initialize by checking the class’s current method table and arity.Because the double is meant to be a lightweight stand‑in, re‑checking the class on every call would add overhead and could mask intentional test‑time modifications. The design therefore ties verification to the moment of creation.
class User
def save; end
end
instance_double and stub the method:user_double = instance_double(User, save: true)
user_double.save # => true
class User
def save(options = {}); end
end
user_double still accepts the call with no arguments because its verification was based on the original signature.user_double.save # => still returns true (no ArgumentError)
new_double = instance_double(User, save: true) # => RSpec::Mocks::MockExpectationError: User does not implement: save
If your test suite mutates a class dynamically, rebuild any instance_double objects after the mutation, or avoid mutating shared classes in tests. There is no configuration to enable automatic re‑verification.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.