如何为活动记录范围编写测试?例如
class Post < ActiveRecord::Base
scope :recent, -> { order("posts.created_at DESC") }
scope :published, -> { where("status = 1") }
end
我使用Rspec进行测试
RSpec.feature Post, :type => :model do
let(:post) { build(:post) }
describe 'test scopes' do
end
end
答案 0 :(得分:8)
假设你有适当的灯具设置,我通常运行一个查询,我希望范围的结果,以及我不喜欢的结果。例如:
describe '#published' do
it "returns a published post" do
expect(Post.published.count).to be(1)
# or inspect to see if it's published, but that's a bit redundant
end
it "does not return unpublished posts" do
expect(Post.published).to_not include(Post.where("status = 0"))
end
end