[Users] Fix unexpected error on creation with duplicate name

find_by_name is not the same as find_by(name:), it is overwritten in the model class.
Luckily there was still a db constraint preventing the name, which is
why the error was raised.
This commit is contained in:
Earlopain 2022-10-20 18:07:16 +02:00
parent d35c33f437
commit 982568a603
No known key found for this signature in database
GPG Key ID: 6CFB948E15246897
2 changed files with 14 additions and 1 deletions

View File

@ -2,7 +2,7 @@ class UserNameValidator < ActiveModel::EachValidator
def validate_each(rec, attr, value)
name = value
rec.errors.add(attr, "already exists") if User.find_by(name: name).present?
rec.errors.add(attr, "already exists") if User.find_by_name(name).present?
rec.errors.add(attr, "must be 2 to 20 characters long") if !name.length.between?(2, 20)
rec.errors.add(attr, "must contain only alphanumeric characters, hypens, apostrophes, tildes and underscores") unless name =~ /\A[a-zA-Z0-9\-_~']+\z/
rec.errors.add(attr, "must not begin with a special character") if name =~ /\A[_\-~']/

View File

@ -92,6 +92,19 @@ class UsersControllerTest < ActionDispatch::IntegrationTest
end
end
context "with a duplicate username" do
setup do
create(:user, name: "test123")
end
should "prevent creation" do
assert_no_difference(-> { User.count }) do
post users_path, params: { user: { name: "TEst123", password: "xxxxx1", password_confirmation: "xxxxx1" } }
assert_match(/Name already exists/, flash[:notice])
end
end
end
context "with email validation" do
setup do
Danbooru.config.stubs(:enable_email_verification?).returns(true)