我的 2 美分(因为我一直在朝着同一个目标努力):
我发现Avdi Grimm 的Objects on Rails一书中非常有用的一种模式是:
class YourObject
def make_related_object
related_object_maker.call
end
def related_object_maker=(maker)
@related_object_maker = maker
end
private
def related_object_maker
@related_object_maker ||= RelatedObject.public_method(:new)
end
end
这使您可以在测试中用 lambda 替换关系,这非常方便。
编辑
describe YourObject do
let(:maker) { lambda { "some value" } }
subject { YourObject.new }
before(:each) do
subject.related_object_maker = maker
end
its(:make_related_object) { should == "some value" }
end