确保super
被调用听起来很像测试实现,而不是行为,并且嘲笑被测对象无论如何都不是一个好主意。我建议只明确指定不同的代码路径
describe "#my_method" do
it "returns :other_symbol when xxx" do
...
end
it "returns :some_symbol when not xxx" do
...
end
end
如果您有很多包含此模块的类,则可以使用共享示例来减少测试中的重复。
shared_examples_for "Something#my_method" do
it "returns :some_symbol" do
expect(subject.my_method).to eq :some_symbol
end
end
describe MyClass do
describe "#my_method" do
context "when xxx" do
subject { ... }
it "returns :other_symbol" do
expect(subject.my_method).to eq :other_symbol
end
end
context "when not xxx" do
subject { ... }
it_behaves_like "Something#my_method"
end
end
end
Update: 如果你really无法预测 mixin 的行为,您可以切换调用哪个方法super
通过包含另一个定义它的模块。
如果你有课C
包括模块M
and N
两者都定义了一个方法f
,然后在C#f
, super
将引用最后包含的模块。
class C
include M
include N
def f
super # calls N.f because it was included last
end
end
如果您将其包含在测试对象的单例类中,那么它不会影响任何其他测试:
describe MyClass do
describe "#my_method" do
it "calls super when not xxx" do
fake_library = Module.new do
def my_method
:returned_from_super
end
end
subject.singleton_class.send :include, fake_library
expect(subject.my_method).to be :returned_from_super
end
end
end
免责声明:这实际上并没有测试 mixinworks, 只是super
被叫。我仍然建议实际测试该行为。