I am making a simple social network with Ruby on Rails. I wanted to add a restriction of certain characters for the profile name when signing up. So, in my User.rb file, I have the following:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me,
:first_name, :last_name, :profile_name
# attr_accessible :title, :body
validates :first_name, presence: true
validates :last_name, presence: true
validates :profile_name, presence: true,
uniqueness: true,
format: {
with: /^[a-zA-Z0-9_-]+$/,
message: "must be formatted correctly."
}
has_many :statuses
def full_name
first_name + " " + last_name
end
end
I set up a test to validate that it works, and this is what the test is:
test "user can have a correctly formatted profile name" do
user = User.new(first_name: '******', last_name: '****', email: '********@gmail.com')
user.password = user.password_confirmation = '**********'
user.profile_name = '******'
assert user.valid?
end
When I run the test, I keep getting the error saying that something is wrong with my assert user.valid? line. So I am thinking I messed up some syntax in my with: /^[a-zA-Z0-9_-]+$/.
The error I am getting is 1) Failure:
test_user_can_have_a_correctly_formatted_profile_name(UserTest) [test/unit/user_test.rb:40]:
But on line 40, it has this piece of code assert user.valid?
Any help is appreciated 🙂
Your syntax is fine.
However, your error message clearly shows you’re using a profile name that doesn’t match.
Are you using some other character in a profile name, such as a space? Or period?
Try it like this:
If the data fails to match, you’ll get nil: