3

パスワード自体を変更する場合を除いて、ユーザーがパスワードを提供せずにアカウントを編集できるようにする場合に、登録コントローラーのカスタム更新アクションを作成する方法について、このdevise wikiドキュメントに従いました。 Devise Wiki - ユーザーがパスワードを入力せずにアカウントを編集できるようにする方法。

しかし、Rspec テストに合格するために何が欠けているのかわかりません。関連するコード スニペットは次のとおりです。

app/controllers/registrations_controller.rb

def update
  @user = User.find(current_user.id)

  successfully_updated = if needs_password?(@user, params)
    @user.update_with_password(devise_parameter_sanitizer.sanitize(:account_update))
  else
    # remove the virtual current_password attribute
    # update_without_password doesn't know how to ignore it
    params[:user].delete(:current_password)
    @user.update_without_password(devise_parameter_sanitizer.sanitize(:account_update))
  end

  if successfully_updated
    set_flash_message :notice, :updated
    # Sign in the user bypassing validation in case their password changed
    sign_in @user, :bypass => true
    redirect_to users_path
  else
    render "edit"
  end
end

仕様/工場/users.rb

FactoryGirl.define do
  factory :user do
    email         { Faker::Internet.email }
    password      'XXXXXXXXX'
    first_name    { Faker::Name.first_name }
    middle_name   { Faker::Name.first_name }
    last_name     { Faker::Name.last_name }
  end
end

仕様/コントローラ/登録_コントローラ_仕様.rb

describe "PUT #update" do
  login_pcp

  let(:user) { FactoryGirl.create(:user, first_name: 'Tom') }

  it "changes user attributes" do
    attrs = FactoryGirl.attributes_for(:user, first_name: 'Jerry')
    attrs.delete(:password)
    put :update, user: attrs
    user.reload
    assigns[:user].should_not be_new_record
    expect(user.first_name).to eq 'Jerry'
    expect(flash[:notice]).to eq 'You updated your account successfully.'
  end
end

仕様を実行すると、次のエラーが表示されます。

Failures:

1) RegistrationsController PUT #update changes user attributes
   Failure/Error: expect(user.first_name).to eq 'Jerry'

   expected: "Jerry"
        got: "Tom"

   (compared using ==)
 # ./spec/controllers/registrations_controller_spec.rb:55:in `block (3 levels) in <top (required)>'

何らかの理由で、更新が保存されません。更新を行うためにパスワードを入力する必要があるかどうかわかりません。どんな助けでも大歓迎です。ありがとう!

4

2 に答える 2

0

私もこの問題に遭遇しましたが、私が見ることができるのは、更新フォームに入力するときに、「現在のパスワード」というフィールドに入力する必要があるためです。フィールドに入力しない限り、データは更新されないためです。factory girl を使用してユーザー データを生成する場合、この値はありません。次のコードに見られるように、私はそれを解決しました。

describe "PATCH #UPDATE" do before :each do @user = create(:user) @old_email = @user.email sign_in @user end context 'valid attributes' do it "updates user attributes" do patch :update, id: @user, user: attributes_for(:user, current_password: "password") expect(@user.reload.email).not_to eq(@old_email) end end end

于 2015-11-02T00:21:14.093 に答える