- Read Tutorial
- Watch Guide Video
In this guide we are going to work on a functionality that does not allow non admins to access the audit log.
Continuing from where we left off in the previous video, open audit_log_spec.rb
. The next test will check this functionality, and we are going to start by logging out the existing user. Then, we'll create a new regular user and login this person. Next, we want the user to visit audit_logs_path
, and we expect that this will take the user to the root_path
. The code is:
# spec/features/audit_log_spec.rb it 'cannot be accessed by non admin users' do logout(:user) user = FactoryGirl.create(:user) login_as(user, :scope => :user) visit audit_logs_path expect(current_path).to eq(root_path) end
Obviously rspec
will fail, and to fix it, go to audit_logs_controller.rb
.
If you think the implementation is going to be similar to what we did in our posts, you're partially right. Here though, we have to switch the order because that's how Pundit
works. If you have code like this,
# app/controllers/audit_logs_controller.rb class AuditLogsController < ApplicationController def index authorize @audit_logs @audit_logs = AuditLog.all end end
rspec
will throw an error saying that it's unable to find the policy. This error is because the value has to be instantiated first before it can be authorized. This is an important concept to know when you're using Pundit
. So, if you reverse this order, the test should pass.
# app/controllers/audit_logs_controller.rb class AuditLogsController < ApplicationController def index @audit_logs = AuditLog.all authorize @audit_logs end end
And it does!