使用Rspec更新密码测试

时间:2015-12-29 05:47:38

标签: ruby rspec

我正在为更新密码编写测试! 这是我的代码:

 def update_password
if @current_user.update(user_params)
  # Sign in the user by passing validation in case their password changed
  # sign_in @user, :bypass => true
  json_success("Password successfully updated")
else
  json_not_found("#{ @user.errors.full_messages.to_sentence}")
end

我的测试是:

context 'update password' do
  def update_password
    patch :update_password, { password: 'password',
                              password_confirmation: 'password' }
  end

  it 'should update user password on user request' do
    expect(user.valid_password?('password')).to eq(false)
    update_password
    user.reload
    puts response.body.inspect
    expect(user.valid_password?('password')).to eq(true)
  end
end

但我一直收到错误:

 1) Api::V2::UsersController patch #update_password update password should update user password on user request
 Failure/Error: expect(user.valid_password?('password')).to eq(true)

   expected: true
        got: false

   (compared using ==)

还有一个问题是如何在其中传递带有身份验证令牌的json标头:谢谢

1 个答案:

答案 0 :(得分:0)

你的规范和控制器应该更接近这个,这应该帮助你已经过了那个错误。 我可以通过@user或@current_user

看到各种其他错误
# app/controllers/some_controller.rb
def update_password
  if @current_user.update(user_params)
    render json: "Password successfully updated"
  else
    render json: @user.errors.full_messages.to_sentence
  end
end

# spec/controllers/some_controller.rb
describe SomeController, type: :controller do
  it '#update_password' do
    params = double(:params, password: 'password', password_confirmation: 'password')
    current_user = double(:current_user)
    expect(current_user).to receive(:update).with(params).and_return(true)
    patch :update_password, params
    expect(response.body).to eq "Password successfully updated"
  end
end 
  

再一次探究如何在其中传递带有身份验证令牌的json标头:谢谢

^^应该是一个不同的SO问题