我正在尝试编写一些规范,并希望消除对数据库的调用,因此我不依赖于实际填充的数据库来运行测试。
现在我真的不知道如何使用 DataMapper stub 关联之间的调用。
下面是两个示例模型:
class Foo
include DataMapper::Resource
property :id, Serial
has n, :bars
end
class Bar
include DataMapper::Resource
property :id, Serial
belongs_to :foo
end
现在我想 stub 对
Foo.first('foobar')
和 Foo.first('foobar').bars
的调用第一个使用
Foo.stub(:first) { #etc }
没有问题,但我不知道如何 stub 对其关联的第二个调用。Foo.stub(:bars) { #etc }
之类的东西不起作用。有谁知道怎么做?这种方法甚至正确吗?
提前致谢。
最佳答案
我会使用一个模拟模型。
foo = mock(Foo).as_null_object
foo.stub(:bars)
Foo.stub(:first).and_return(foo)
使用 as_null_object 的原因是,当被问及它是否重新分配给它没有被告知期望的方法时,默认情况下 RSpec 将返回 false。
如果这不起作用,则创建一个 foo 实例。
foo = Foo.create(:example => "data") #Or create with a factory a factory
foo.stub(:bars)
Foo.stub(:first).and_return(foo)
然后当你这样做时:
Foo.first('foobar').bars
它将使用第 2 行的 stub ,因为第一次调用将返回 foo 的那个实例。
关于ruby - 如何 stub DataMapper 与 RSpec2 的关联?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7091502/