查找最后创建的记录 RSpec 测试
Find last created record RSpec test
我如何编写测试来查找最后创建的记录?
这是我要测试的代码:
Post.order(created_at: :desc).first
我也在用 factorybot
如果您调用了您的方法 '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' 方法调用的结果 - 只是它被调用了。
接受的答案不正确。只需执行 Post.last
即可按 ID
对帖子进行排序,而不是按创建时间排序。
https://apidock.com/rails/ActiveRecord/FinderMethods/last
如果您使用顺序 ID(理想情况下您不应该使用),那么显然这会起作用,但如果不是,则您需要指定要排序的列。所以要么:
def self.last_post
order(created_at: :desc).first
end
或:
def self.last_post
order(:created_at).last
end
就我个人而言,我希望将此作为一个范围而不是专用方法。
scope :last_created -> { order(:created_at).last }
这允许您使用其他范围创建一些不错的链,例如,如果您有一个可以找到特定 user/account 的所有帖子,那么您可以非常干净地链接它:
Post.for_user(user).last_created
当然你也可以链接方法,但如果你处理的是查询接口方法,我觉得范围更有意义,而且往往更简洁。
如果您想测试它 returns 是否是正确的记录,在您的测试中您可以这样做:
let!(:last_created_post) { factory_to_create_post }
. . .
it "returns the correct post"
expect(Post.last_post).to eq(last_created_post)
end
如果您想进行更好的测试,您可以在最后一条记录之前创建几条记录,以验证被测方法正在提取正确的结果,而不仅仅是 a来自单一记录。
我如何编写测试来查找最后创建的记录?
这是我要测试的代码:
Post.order(created_at: :desc).first
我也在用 factorybot
如果您调用了您的方法 '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' 方法调用的结果 - 只是它被调用了。
接受的答案不正确。只需执行 Post.last
即可按 ID
对帖子进行排序,而不是按创建时间排序。
https://apidock.com/rails/ActiveRecord/FinderMethods/last
如果您使用顺序 ID(理想情况下您不应该使用),那么显然这会起作用,但如果不是,则您需要指定要排序的列。所以要么:
def self.last_post
order(created_at: :desc).first
end
或:
def self.last_post
order(:created_at).last
end
就我个人而言,我希望将此作为一个范围而不是专用方法。
scope :last_created -> { order(:created_at).last }
这允许您使用其他范围创建一些不错的链,例如,如果您有一个可以找到特定 user/account 的所有帖子,那么您可以非常干净地链接它:
Post.for_user(user).last_created
当然你也可以链接方法,但如果你处理的是查询接口方法,我觉得范围更有意义,而且往往更简洁。
如果您想测试它 returns 是否是正确的记录,在您的测试中您可以这样做:
let!(:last_created_post) { factory_to_create_post }
. . .
it "returns the correct post"
expect(Post.last_post).to eq(last_created_post)
end
如果您想进行更好的测试,您可以在最后一条记录之前创建几条记录,以验证被测方法正在提取正确的结果,而不仅仅是 a来自单一记录。