Note that there are some explanatory texts on larger screens.

plurals
  1. POStaying DRY while testing a controller, authorized via CanCan
    text
    copied!<p>I'm retroactively writing some tests, using RSpec, for a Rails project.</p> <p>I'm using the CanCan gem to provide authorization. I decided to write a spec that will test the <code>ability.rb</code> model. I then went on to test my remaining models.</p> <p>I've moved on to controllers, and I've run into a huge snag: I'm testing my abilities all over again!</p> <p>Basically, I have to stub out a series of models, and stub out their associations; otherwise the response just returns <code>403 Forbidden</code>.<br> The reason for this, is that the controller is basically in charge of worrying about authorization.</p> <p>I'm not quite sure where to go from here. I'm stubbing out up to 6 models, just to write a single test. I <em>know</em> the abilities work, that's what <code>ability_spec.rb</code> is for.</p> <p>So this question is really 2-fold:</p> <ol> <li>Should I be testing the ability model separately?</li> <li>Should the controller tests be concerned with proper permissions?</li> </ol> <hr> <p><strong>Edit</strong> require 'spec_helper' include Devise::TestHelpers # to give your spec access to helpers</p> <pre><code>describe TokensController do before(:each) do @mock_user = User.new(:username =&gt; "bob", :email =&gt; "user@user.com", :password =&gt; "longpassword") @mock_user.role = "admin" sign_in @mock_user #Ability.stub!('can').and_return(true) end it "should let me see grids/:g_id/tokens index" do test_grid = mock_model(Grid) test_token = mock_model(Token) Grid.stub!(:find).and_return(test_grid) Token.stub!(:find).and_return(test_token) get 'index' a1 = Ability.new(@mock_user) a1.can?(:index, Token).should be_true # This line works fine; as it should puts response.status #This returns 403, which means CanCan::AccessDenied was raised end end </code></pre> <p>Thanks,<br> Robbie</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload