0
以下是僅用於rails-api
的應用程序。控制器的before_save方法在測試中不被調用
在users_controller.rb
def sign_up
@user = User.new(user_params)
if @user.save
user = {}
user[:name] = @user.name
user[:email] = @user.email
user[:access_token] = @user.auth_token
user[:message] = "Successfully Signed up"
render json: user, status: 200
else
render json: @user.errors, status: :unprocessable_entity
end
end
private
def user_params
params.permit(:name, :email, :password, :password_confirmation)
end
在模型/ user.rb
attr_accessor :password
before_save :encrypt_password, :generate_token
VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX } , uniqueness: { case_sensitive:false }
validates :password, :confirmation => true, presence: true, :length => {:within => 6..20}
validates_presence_of :password_salt, :password_hash
validates_presence_of :auth_token
在測試/控制器/ users_controller_test.rb
test "should create user" do
assert_difference('User.count') do
post :sign_up, {email: '[email protected]', name: 'user_3', password: 12345678, password_confirmation: 12345678}
end
end
用戶模型的屬性有:
name email password_hash password_salt auth_token
上述試驗失敗b'cos @ user.errors顯示
<ActiveModel::Errors:0x007fd826117140 @base=#<User id: nil, name: "user_3", email: "[email protected]", password_hash: nil, password_salt: nil, auth_token: nil, created_at: nil, updated_at: nil>, @messages={:password_salt=>["can't be blank"], :password_hash=>["can't be blank"], :auth_token=>["can't be blank"]}>
在@user.save
before_save :encrypt_password, :generate_token
不叫。
使用gem 'bcrypt'
將密碼存儲爲散列。
我該如何糾正?
謝謝。這工作。在開發過程中,它不會導致任何錯誤。但在測試中它確實。我有點部分理解這一點。你能幫我在這裏嗎? – rAzOr
也許在開發中你會對現有用戶進行測試嗎? –
不,它是註冊操作。所以一個新用戶。 – rAzOr