Sto lavorando a un progetto di rotaie in cui utilizzo CanCan per autorizzare le mie risorse. Quando un utente non ha effettuato l'accesso e prova a inviare un "talk" (tramite una richiesta di modulo Ajax), CanCan solleva correttamente un 401 con {"status":"error","message":"You must be logged in to do that!"}
come risposta (l'ho verificato nel browser usando firebug). Tuttavia, nel mio test ottenere un codice di 302 risposta piuttosto che un 401:Come posso utilizzare RSpec per testare il codice di risposta su un'autenticazione CanCan fallita?
class TalksController < ApplicationController
authorize_resource
def create
@talk = current_user.talks.build(params[:talk])
respond_to do |format|
if @talk.save
response = { :redirect => talk_path(@talk) }
format.html { redirect_to @talk, notice: 'Talk was successfully created.' }
format.json { render json: response, status: :created, }
else
format.html { render action: "new" }
format.json { render json: @talk.errors, status: :unprocessable_entity }
end
end
end
end
talks_controller_spec.rb:
describe TalksController do
describe "POST create" do
context "when not signed in" do
it "should not assign talk" do
post :create
assigns[:talk].should be_nil
end
it "should respond with a 401" do
post :create
response.response_code.should == 401
end
end
end
end
Il primo esempio qui incluso successo (assegna [Talk] non vengono assegnati), ma il secondo non è:
1) TalksController POST create when not signed in should respond with a 401
Failure/Error: response.response_code.should == 401
expected: 401
got: 302 (using ==)
# ./spec/controllers/talks_controller_spec.rb:53:in `block (4 levels) in <top (required)>'
Non so esattamente cosa sta succedendo. C'è un modo per testare il codice di risposta effettivo restituito al browser? O un modo migliore posso testare l'autorizzazione?
Si potrebbe provare a cambiare le specifiche per leggere 'post: create,: format =>: json' e vedere se questo aiuta. – zetetic
Grazie per il suggerimento! Sfortunatamente, ottengo ancora lo stesso codice 302 dopo aver aggiunto: format =>: json. –
Hai guardato il registro di prova? – zetetic