ishwr
ishwr

Reputation: 745

Testing default scope in Rails

all. I am having difficulties to write a test for my model with default scope. I have a user model with attribute active_status which can be changed by admin. I gave the user default scope active_status true. default_scope(:active_status => true ) In Admin page I used unscoped so that Admin can see all the users. How to write this test? Thanks

Upvotes: 0

Views: 342

Answers (2)

Daniël Zwijnenburg
Daniël Zwijnenburg

Reputation: 2560

you could so something along the lines of this:

context "scopes" do
  describe "default_scope" do
    before do 
      create(:user, active_status: true) 
      create(:user, active_status: false)
    }

    context "with default scope" do
      subject { User.all }

      it { should have(1).user }
    end

    context "without default scope" do
       subject { User.unscoped.all }

      it { should have(2).users }
    end
  end
end

note: I'm using RSpec and FactoryGirl.

note2: You can consider this as an anti pattern, because the default_scope is a protected method. But this is what you asked for.

Upvotes: 1

CDub
CDub

Reputation: 13364

Sounds like all you need to do is write a test for the admin page that creates an inactive user and verifies that when the admin page loads, one result is returned... Am I missing something?

Upvotes: 1

Related Questions