以下是一些代碼片段 - 如果您需要更多,請讓我知道,我會發布它。Rails教程 - 無法獲得修補程序測試工作 - 修補程序無法識別的方法
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:edit, :update]
before_filter :correct_user, only: [:edit, :update]
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]) # user_params
flash[:success] = "Profile updated"
sign_in @user
redirect_to @user
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
# Before filters
def signed_in_user
redirect_to signin_url, notice: "Please sign in." unless signed_in?
end
def correct_user
@user = User.find(params[:id])
redirect_to(root_path) unless current_user?(@user)
end
end
,然後單元測試...
describe "authorization" do
...
describe "submitting a PATCH request to the Users#update action" do
before { patch user_path(wrong_user) }
specify { expect(response).to redirect_to(root_path) }
end
如果我跑,我得到的消息:
FailureError: before { patch user_path(wrong_user) } NoMethodError: undefined method `patch' for # RSpec::Core::ExampleGroup::Nested_3::Nested_1::Nested_3::Nested_2::Nested_2:0x...
如果我改變的補丁後,我得到這個。 ...
FailureError: before { post user_path(wrong_user) } ActionController::RoutingError: No route matches [POST] "users/1497"
put的錯誤實際上表明測試正在重定向到登錄路徑,但是當我在瀏覽器中測試它時,它將按照預期重定向到根路徑。我想知道我的會議是否沒有堅持參加考試。我還記得我們給我一些有點像在此之前在之前的測試中麻煩......
下面是測試代碼的其餘部分:
describe "for wrong user" do
let(:user) { FactoryGirl.create(:user) }
let(:wrong_user) { FactoryGirl.create(:user, email: "[email protected]") }
before { sign_in user, no_capybara: true }
describe "visiting Users#edit page" do
before { visit edit_user_path(wrong_user) }
it { should_not have_title(full_title('Edit user')) }
end
describe "submitting a PATCH request to the Users#update action" do
before { put user_path(wrong_user) }
specify { expect(response).to redirect_to(root_path) }
end
end # end for wrong user
看來我的問題是,我的用戶沒有登錄。當我在瀏覽器中測試時,一切正常,但是當我運行單元測試,實際上把我重定向到登錄頁面。然而,我有一個先前的測試,它依賴於那個有效的sign_in方法... – josiah
好的,我以爲你使用的是rails 3.2,下次請正確標記你的問題:)很高興你發現修復無論如何。歡呼 – Benj
那麼,你是否正確 - 把工作,這顯示了真正的錯誤,哈哈,這是當提交一個放錯請求更新爲錯誤的用戶,我被重定向到錯誤的頁面。 – josiah