假设我们有类:
class Post
def save
# implementation
end
def self.find(id)
#implementation
end
end
我努力测试 #save
和 .find
,我已经:
describe '#save' do
it 'saves the post' do
subject.save
created = Post.find(subject.id)
expect(created).to eq(subject)
end
end
describe '.find' do
it 'finds the post' do
subject.save
created = Post.find(subject.id)
expect(created).to eq(subject)
end
end
在 #save
方法的情况下,我想检查副作用,在 .find
的情况下,我想测试返回值。如何在不重复规范的情况下处理这种情况?
最佳答案
在这种情况下,要隔离save
和find
操作,您需要模拟存储库。
无论您是写入数据库、文件系统、缓存还是其他任何东西 - 您都可以模拟它以期望保存功能,或者设置它(在测试开始之前)以确保 查找
有效。
对于大多数存储库实现,都有 gem 来模拟它们(Factory Girl 用于关系数据库,FakeFS 用于文件系统),但如果您有一些没有人听说过的异国情调的存储库,您可以自己推出。
通过这种方式,您可以在不使用 find
的情况下测试 save
,反之亦然。
关于ruby-on-rails - 如何测试 RSpec 中的相关(耦合)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23722843/