我怎么能写一个测试来找到最后创建的记录?
这是我要测试的代码:
Post.order(created_at: :desc).first
我也在使用工厂机器人
如果你已经调用了你的方法'last_post':
def self.last_post
Post.order(created_at: :desc).first
end
然后在你的测试中:
it 'should return the last post' do
expect(Post.last_post).to eq(Post.last)
end
另一方面,编写代码的最简单方法就是
Post.last
你不应该真正测试ruby方法的结果(你应该确保调用正确的ruby方法),所以如果你这样做:
def self.last_post
Post.last
end
那你的测试可能是:
it 'should send the last method to the post class' do
expect(Post).to receive(:last)
Post.last_post
end
你没有测试'last'方法调用的结果 - 只是调用它。