以下是一些代码片段 - 如果您需要更多代码,请告诉我,我会发布。
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:在{patch user_path(wrong_user)}之前 NoMethodError: #RSpec :: Core :: ExampleGroup :: Nested_3 :: Nested_1 :: Nested_3 :: Nested_2 :: Nested_2:0x ...
的未定义方法`patch'
如果我将补丁更改为发布,我会得到这个......
FailureError:在{post user_path(wrong_user)}之前 ActionController的:: RoutingError: 没有路线匹配[POST]“users / 1497”
put的错误实际上表示测试被重定向到登录路径,但是当我在浏览器中测试它时,它会按预期重定向到根路径。我想知道我的会议是否坚持不懈。我记得在以前的测试之前让我给这样的麻烦......
以下是测试代码的其余部分:
describe "for wrong user" do
let(:user) { FactoryGirl.create(:user) }
let(:wrong_user) { FactoryGirl.create(:user, email: "wrong@example.com") }
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
答案 0 :(得分:3)
patch
,您使用的是Rails 3.2(这是您问题标签中提到的内容),您需要使用put
而不是