1

这是一些代码片段 - 如果您需要更多代码,请告诉我,我会发布它。

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:在 { 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
4

1 回答 1

3

patch存在于 Rails 4 中,您是否正在使用 Rails 3.2(这就是您的问题标签中提到的),您需要put改用

于 2013-07-23T03:35:00.960 回答