How can I write tests for active record scopes? for example
class Post < ActiveRecord::Base
scope :recent, -> { order("posts.created_at DESC") }
scope :published, -> { where("status = 1") }
end
I'm using Rspec for testing
RSpec.feature Post, :type => :model do
let(:post) { build(:post) }
describe 'test scopes' do
end
end
Assuming that you have the appropriate fixtures setup, I usually run a query where I expect results from the scope, and one where I don't. For example:
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