Last active
November 12, 2022 03:50
-
-
Save usutani/511ca0913e0b3c4625bfdd4f3f273814 to your computer and use it in GitHub Desktop.
try_account --- 更新時にnilで保存できないようにしました。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# bundle add bcrypt | |
# rails g scaffold Account email password_digestx | |
# rails db:migrate | |
class Account < ApplicationRecord | |
has_secure_password validations: false | |
validate do |record| | |
record.errors.add(:password, :blank) unless record.password_digest.present? | |
end | |
validates :password, format: { with: /\A[a-z0-9]+\z/i }, length: { in: 8..30 }, on: :create, unless: -> { password_digest.blank? } | |
validates :password, format: { with: /\A[a-z0-9]+\z/i }, length: { in: 8..30 }, on: :update, allow_nil: true | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "test_helper" | |
class AccountTest < ActiveSupport::TestCase | |
test "生成" do | |
account = Account.new | |
assert account.invalid? | |
assert_equal ["Password can't be blank"], account.errors.full_messages | |
account.password = "!!!" | |
assert account.invalid? | |
assert_equal ["Password is invalid", "Password is too short (minimum is 8 characters)"], account.errors.full_messages | |
account.password = "12345678" | |
assert account.valid? | |
assert account.save! | |
end | |
test "更新" do | |
assert account = Account.create!(password: "12345678") | |
account = Account.find(account.id) # 再取得する。reloadではpasswordが残る。 | |
assert_nil account.password | |
assert account.valid? | |
account.password = "" | |
assert account.valid? | |
assert !account.password_digest_changed? | |
assert_nil account.password, "空文字列は設定できない。" | |
account.password = nil | |
assert account.invalid? | |
assert account.password_digest_changed? | |
assert_nil account.password, "nilは設定できる。保存はできない。" | |
assert_equal ["Password can't be blank"], account.errors.full_messages | |
account.password = "!!!" | |
assert account.invalid? | |
assert_equal ["Password is invalid", "Password is too short (minimum is 8 characters)"], account.errors.full_messages | |
account.password = "12345678" | |
assert account.valid? | |
assert account.save! | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment