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

ltd*_*dev 3 testing rspec ruby-on-rails rspec-rails

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

class Post < ActiveRecord::Base
  scope :recent, -> { order("posts.created_at DESC") }
  scope :published, -> { where("status = 1") }
end
Run Code Online (Sandbox Code Playgroud)

我正在使用Rspec进行测试

RSpec.feature Post, :type => :model do
  let(:post) { build(:post) }

  describe 'test scopes' do
  end
end
Run Code Online (Sandbox Code Playgroud)

Gav*_*ler 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
Run Code Online (Sandbox Code Playgroud)