【发布时间】:2020-04-27 17:00:03
【问题描述】:
我需要用测试覆盖我的 Ruby on Rails 代码。我使用 RSpec 进行测试。
有什么方法可以模拟基于实例的调用? (kind_of?)。我想测试给定父类的孩子是否被调用。我希望有类似allow_any_kind_of 的方法,类似于allow_any_instance_of。但是我找不到类似的东西。
这是我的代码示例。
我有Base 班级和一些孩子。在测试中,使用什么确切的孩子并不重要。
class Parent
def my_method; end
end
class ChildA < Parent; end
class ChildB < Parent; end
class App
def apply
[ChildA.new, ChildB.new].all? { |c| c.my_method }
end
end
我的 RSpec 测试。它失败是因为 ChildA 或 ChildB 都不是 Parent 类的实例。我可以有多个 allow_any_instance_of 来覆盖所有 Parent 的孩子,但我想保持简单,因为在实际代码中会有更多的孩子。
context "#apply" do
before do
allow_any_instance_of(Parent).to receive(:my_method).and_return(true)
end
it "returns true" do
expect(subject.apply).to be_truthy
end
end
【问题讨论】:
标签: ruby-on-rails ruby rspec rspec-rails