Testing and cancan in controller specifications (rspec)

Now that I am working with CanCan and Devise, I need to add my tests.

Should I count on doubling the number of tests, maybe more? I need to check everything as a "guest", and then check as a user as well as an administrator.

With rspec, how would you formulate this?

describe "GET edit" do
    login_admin
    it "assigns the requested forum_topic as @forum_topic" do
      ForumTopic.stub(:find).with("37") { mock_forum_topic }
      get :edit, :id => "37"
      response.should redirect_to( new_user_session_path )
    end

    it "assigns the requested forum_topic as @forum_topic" do
      ForumTopic.stub(:find).with("37") { mock_forum_topic }
      get :edit, :id => "37"
      assigns(:forum_topic).should be(mock_forum_topic)
    end
end

auxiliary module

  def login_admin
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:admin]
      sign_in Factory.create(:admin)
    end
  end

  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      @user = Factory.create(:user)
      sign_in @user
    end
  end
+3
source share
1 answer

What is usually done when testing CanCan, he tests the capabilities file himself.

For example, if you test that in your application you will not be able to view a specific forum if you are not subscribed, you can check it like this:

@user = Factory.create(:user)
@forum = Factory.create(:forum)

describe "User ability" do
  it "Should be able to view forums" do
    @ability = Ability.new(@user)
    @ability.should be_able_to(:show, @forum)
  end
end

describe "nil ability" do
  it "Should be not be able to view forums if not signed in" do
    @ability = Ability.new(nil)
    @ability.should_not be_able_to(:show, @forum)
  end
end

This is just an example.

: https://github.com/ryanb/cancan/wiki/Testing-Abilities

, , , capybara .

+2

All Articles