0
中看到簽名,所以我一直在使用Michael Hartl的教程一段時間,我可以說這真的很有用,但有一個問題,我覺得它不在教程的一部分。因此,在「9.2.2要求正確的用戶」一章中,我們將檢查用戶是否既不能訪問其他用戶的編輯頁也不能提交直接的PUT請求。Ruby on Rails RSpec放置方法未在用戶
describe "as wrong user" do
let(:user) { FactoryGirl.create(:user) }
let(:wrong_user) { FactoryGirl.create(:user, email: "[email protected]") }
before { sign_in user }
describe "visiting Users#edit page" do
before { visit edit_user_path(wrong_user) }
it { should_not have_selector('title', text: full_title('Edit user')) }
end
describe "submitting a PUT request to the Users#update action" do
before { put user_path(wrong_user) }
specify { response.should redirect_to(root_path) }
end
end
只要一切似乎是正確的,但測試失敗:
1) Authentication authorization as wrong user submitting a PUT request to the Users#update action ←[31mFailure/Error:←[0m ←[31mspecify { response.should redirect_to(root_path }←[0m←[31mExpected response to be a redirect to <http://www.example.com/> but was a redirect to <http://www.example.com/signin>←[0m←[36m # ./spec/requests/authentication_pages_spec.rb:107:in `block (5 levels) in <top (required)>'←[0m
這裏的用戶控制器:
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:index, :edit, :update]
before_filter :correct_user, only: [:edit, :update]
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
sign_in @user
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
def edit
end
def update
if @user.update_attributes(params[:user])
flash[:success] = "Profile updated"
sign_in @user
redirect_to @user
else
render 'edit'
end
end
private
def signed_in_user
unless signed_in?
puts "No user signed in"
store_location
redirect_to signin_path, notice: "Please sign in."
end
end
def correct_user
@user = User.find(params[:id])
puts "Incorrect user" unless current_user?(@user)
redirect_to(root_path) unless current_user?(@user)
end
end
因此,大家可以看到的問題是,當使用RSpec的放法,即使在檢查合適的用戶之前測試也會失敗,因爲它認爲沒有用戶登錄。 這是一個很容易被忽略的小問題(不正確的用戶不能使用d直接請求PUT),但這對我來說是一個難題,爲什麼它不能正確工作,我已經很久沒有得到答案了。
謝謝,史蒂夫,但sign_in已被定義,所以它似乎並非如此。 –
雖然看起來沒有登錄。您可以嘗試從測試中調用'save_and_open_form'來查看頁面上是否有任何錯誤消息。或者,log/test.log中是否有任何線索? – Steve