I'm writing an app with Rails that will have REST API. Most of the controllers aren't accessible unless a user has been authorized. It's done by inserting a method that checks user's privilege in before_action hooks in controllers. I want to test that unauthorized users can not access certain parts of the API. Currently I do it like that:
require 'rails_helper'
RSpec.describe RoomsController, type: :controller do
...
describe "while unauthenticated" do
before do
logout
end
def expect_unauth
expect(response).to have_http_status(:unauthorized)
end
it "GET #index returns http unauthorized" do get :index; expect_unauth end
it "GET #show returns http unauthorized" do get :show, {id: 1}; expect_unauth end
it "DELETE #destroy returns http unauthorized" do delete :destroy, {id: 1}; expect_unauth end
it "POST #create returns http unauthorized" do post :create, {id: 1}; expect_unauth end
it "PUT #update returns http unauthorized" do put :update, {id: 1}; expect_unauth end
end
It works, but it's pretty much the same for every controller. How can I make such a test without copy-pasting this code in every controller? Should I even test for it or since it's a pretty simple I should just assume that it works and write tests for a specific to controller functionality?
Also, does it even belong in controller specs? Maybe it should be a request spec?
Aucun commentaire:
Enregistrer un commentaire