我的用户#upcate方法似乎按预期工作。从我的前端请求执行此方法时,会发生成功更新。然而,该方法的测试失败了。
对于我的测试,我将用户登录,然后将返回的auth_token
附加到请求标头中。
以下是测试:
test "should successfully update valid email" do
old = @user.auth_token
post api_login_url, params: { session: @credentials }
@user.reload
assert_not_equal old, @user.auth_token
old_user = @user
@request.headers["Authorization"] = @user.auth_token
patch "/api/users/" + @user.id.to_s, params: { email: "new@me.com", password: "testtest" }, headers: @request.headers
assert_response 201
assert_equal "new@me.com", User.find(@user.id).email
end
错误:
Expected: "new@me.com"
Actual: "test@woohoo.com"
在我的控制器中(@user
已设置):
before_action:authenticate_with_token!,only:[:update,:destroy]
before_action:set_user,only:[:show,:update,:destroy,:confirm,:posts,:comments]
wrap_parameters:user,include:[:username,:email,:password,:password_confirmation]
def update
if @user.update(user_params)
render json: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end
def user_params
params.require(:user).permit(:username, :email, :password, :password_confirmation, :confirmation_code, :confirmed)
end
用户模型:
require 'json_web_token'
class User < ApplicationRecord
before_save { email.downcase! }
before_create :generate_authentication_token!
before_update :reset_confirmed!, :if => :email_changed?
has_secure_password
has_many :posts
has_many :comments
has_many :votes
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
validates :username, presence: true, length: { maximum: 24 }, uniqueness: { case_sensitive: false }
validates :password, presence: true, length: { minimum: 8 }
validates :auth_token, uniqueness: true
def generate_authentication_token!
begin
self.auth_token = JsonWebToken.encode('id' => self.id, 'username' => self.username)
end while self.class.exists?(auth_token: auth_token)
end
def destroy_token!
self.auth_token = nil
end
def reset_confirmed!
self.confirmed = false
end
end
如果有人会问,我已尝试删除before_update :reset_confirmed!
来电。
我尝试过多种不同的方式重写测试。 assert_response 201
不会失败。
Rails版本:5.0.0.beta2
Ruby版本:2.2.3(x86_64-darwin15)
答案 0 :(得分:1)
你需要包装你的参数:
patch "/api/users/" + @user.id.to_s,
params: { user: { email: "new@me.com", password: "testtest" }},
headers: @request.headers
但是我很惊讶你没有得到例外(require(:user)
应该在params[:user]
缺少的情况下提出一个例外),所以让我知道它是否有效。