mardi 16 juin 2020

How to test login actions from an RSpec test?

We need to test the access-control methods of an app, to make sure only users with the correct roles are allowed to perform certain operations. We determine the role of the user by looking in the session to see who is logged in.

Our tests attempt to change the role of the user and make sure that actions that are supposed to be disallowed for that role are in fact disallowed. However, the tests don't work because, in the current versions of Rails, it is not possible to set the session variable in feature specs.

We need a way to populate the session variable in the tests for our authorization methods to work as intended, failing which we could use a workaround. How can we populate the session variable or work around it to test authorization in our application?

Here's the code in the authorization file testing if a user has logged in (which gets called for multiple actions within tests):

  def user_logged_in?
    !session[:user].nil?
  end

And the code in spec/rails_helper.rb which tries to populate the session variable when a user is being stubbed:

def stub_current_user(current_user, current_role_name = 'Student', current_role)
    allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(current_user)
    allow_any_instance_of(ApplicationController).to receive(:current_role_name).and_return(current_role_name) 
    allow_any_instance_of(ApplicationController).to receive(:current_role).and_return(current_role)
    session[:user] = current_user
end

Which causes the following error to arise:

undefined local variable or method `session' for <RSpec::ExampleGroups::AirbrakeExpectionErrors:0x000000138599a0>

Aucun commentaire:

Enregistrer un commentaire