如何编写活动记录范围的测试?

时间:2017-02-26 18:59:28

标签: ruby-on-rails testing rspec rspec-rails

如何为活动记录范围编写测试?例如

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

1 个答案:

答案 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