Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9167491
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T15:24:13+00:00 2026-06-17T15:24:13+00:00

I am trying to test the user authentication for the Farm model, in this

  • 0

I am trying to test the user authentication for the Farm model, in this case for the :user role which has read access to all farms when being logged-in (as the guest user aka. anonymous has too).

# /models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    # Create guest user aka. anonymous (not logged in) when user is nil.
    user ||= User.new

    if user.has_role? :admin
      can :manage, :all
    else # guest user aka. anonymous
      can :read, :all
      # logged in user
      if user.has_role? :user
        can :create, Farm
        can :manage, Farm, :user_id => user.id
      end
    end

  end
end

…

# /controllers/api/v1/farms_controller.rb
class Api::V1::FarmsController < ActionController::Base

    load_and_authorize_resource
    rescue_from CanCan::AccessDenied do |exception|
        redirect_to farms_path, alert: exception.message
    end
    respond_to :json

    def index
        # Next line might be redundant refering to the CanCan wiki. See below..
        @farms = Farm.accessible_by(current_ability, :read)
        respond_with(@farms)
    end
end

…

# /spec/api/v1/farm_spec.rb
require "spec_helper"

describe "/api/v1/farms" do
    let(:user) { create(:user) } # lets call this user1 in the discussion
    let(:token) { user.authentication_token }

    before do
        user.add_role :user
        create(:farm, user: user, name: "Testfarm")
        create(:farm, name: "Access denied")
        @ability = Ability.new(user)
    end

    context "farms viewable by this logged-in user" do
        let(:url) { "/api/v1/farms" }
        it "json" do
            get "#{url}.json"

            farms_json = Farm.accessible_by(@ability, :read).to_json

            assert last_response.ok?
            last_response.body.should eql(farms_json)
            last_response.status.should eql(200)

            farms = JSON.parse(last_response.body)

            farms.any? do |farm|
                farm["name"] == "Testfarm"
            end.should be_true

            farms.any? do |farm|
                farm["name"] == "Access denied"
            end.should be_true

        end
    end
end

The problem

When I inspect farms_json I can see it contains only the Testfarm. When I inspect the last_response I can see it contains both the Testfarm and Access denied. This is strange since I use the same accessible_by method both in the spec and the index action. The setup I use is described in the wiki of the CanCan gem entitled Fetching Records.

The useless workaround

When I add the user user to the farm Access denied, such as …

create(:farm, user: user, name: "Access denied")

… then the test succeeds.

The questions

  1. Why is the “Access denied” farm not returned although it can be read by any user (including guest users)?
  2. Does get "#{url}.json" actually consider the status of the user? Is this all done by load_and_authorize_resource in the FarmsController?
  3. The wiki mentions that @farms = Farm.accessible_by(current_ability, :read) can be left out since “this is done automatically by load_resource for the index action”. Does this apply to my situation?

Experiments

I created another user “user2” and another farm “My little farm”. I linked those to each other. This way the database in the example contains three farms alltogether:

  • Farm “Testfarm” associated to user1
  • Farm “Access denied” associated to no user
  • Farm “My little farm” associated to user2.

When I run Farm.accessible_by(Ability.new(user1), :read) I still only receive “Testfarm”.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T15:24:15+00:00Added an answer on June 17, 2026 at 3:24 pm

    The answer to my question consists of multiple parts. I hope this clarifies the setup to everyone else who deals with a similar configuration.

    1. Ability Precedence

    First of all please mind that the order of ability rules does matter as described in Ability Precedence. After realizing this fact I came up with an updated set of ability rules.

    # /models/ability.rb
    class Ability
      include CanCan::Ability
    
      def initialize(user)
        # Create guest user aka. anonymous (not logged-in) when user is nil.
        user ||= User.new
    
        if user.has_role? :admin
          can :manage, :all
        else
          # logged in user
          if user.has_role? :user
            can :manage, Farm, :user_id => user.id
            can :create, Farm
          end
           # guest user aka. anonymous
          can :read, :all
        end
      end
    end
    

    2. FarmsContoller

    Keep it simple in the index action. load_and_authorize_resource is your friend.

    # /controllers/api/v1/farms_controller.rb
    class Api::V1::FarmsController < ActionController::Base
    
        load_and_authorize_resource
        rescue_from CanCan::AccessDenied do |exception|
            redirect_to farms_path, alert: exception.message
        end
        respond_to :json
    
        def index
            respond_with(@farms)
        end
    end
    

    3. Get request with authentication token

    Do not forget to pass the token when you request data from the farms controller.

    # # /spec/api/v1/farm_spec.rb
    get "#{url}.json", auth_token: :token
    

    The token must be added in the User model as follows.

    # app/models/user.rb
    class User < ActiveRecord::Base
        before_save :ensure_authentication_token
    

    And the name of the method can be configured in the initializer of Devise.

    # config/initializers/devise.rb
    config.token_authentication_key = :auth_token
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In my windows form application, I'm trying to test the user's ability to access
I'm trying to test that a UserProfile model is created as a new User
I'm trying to create a database in couchdb, which has an admin user/password set,
Im trying to test my successfully creates a new user after login (using authlogic).
I'm trying to test an OpenFileDialog that is created when the user clicks on
Trying to test the option of replacing our internal data access layer with Entity
just trying to test for equality in this piece of code, but getting a
I am trying to test user credentials on a web application that uses POST
I'm trying to get a test signing in using basic authentication. I've tried a
I am trying to set up a basic user authentication - I have the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.