my model has default_scope(:order => 'created_at' ) my tests (rspec, factory girl, shoulda, etc.) are:
require 'spec/spec_helper.rb'
describe CatMembership do
context "is valid" do
subject { Factory.build(:cat_membership) }
it { should be_valid }
it { should belong_to :cat}
it { should belong_to :cat_group}
it { should have_db_column(:start_date)}
it { should have_db_column(:end_date)}
end
end
According to latest conventions of
RSpec
expect
is recommended instead ofshould
so, better answer would beexpect(CatMembership.scoped.to_sql).to eq(CatMembership.order(:created_at).to_sql)
However, lately
Model.scoped
is deprecated so it is recommended to useModel.all
insteadexpect(CatMembership.all.to_sql).to eq(CatMembership.order(:created_at).to_sql)
DRY It Up, Use Shared Examples
Most likely, you'll have more than one model with a similar default scope (if not, mostly ignore this method) so you can put this Rspec example into a shared_example where you can call it from a variety of model specs.
My preferred method of checking a default scope is to make sure the default
ActiveRecord::Relation
has the expected clause (order
orwhere
or whatever the case may be), like so:spec/support/shared_examples/default_scope_examples.rb
And then in your
CatMembership
spec (and any other spec that has the same default scope), all you need to is:spec/models/cat_membership_spec.rb
Finally, you can see how this pattern can be extended to all sorts of default scopes and keeps things clean, organized and, best of all, DRY.
I would rather have this tested using a query and checking the results, but if you really must do it, one possible solution would be something like this for Rails 3:
And on Rails 2:
But I would not say these solutions are ideal since they show a lot of knowledge of the implementation (and you can see the implementation varies with different Rails versions).
Creating sample data, running an usual all query and checking the result is correctly ordered might have been simpler, would be closer to real unit testing and would work even as you upgrade your rails version.
In this case it would possibly be:
It's much more verbose, but it's going to work even as you move forward on rails.
And now I have just noticed who asked the question :D