Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Build a Simple Ruby on Rails Application Writing Tests Validating Format

Jonathan Martínez
Jonathan Martínez
13,375 Points

Profile Name always raising error!!!

I've done all the steps, but no matter what I do; even if the profile name doesn't contain any space, it will raise an error saying profile name must be formatted correctly.

This is my code:

user_test.rb

  test "a user should have a profile name without spaces" do
    user = User.new

    user.profile_name = "Profile name with spaces"

    assert !user.save
    assert !user.errors[:profile_name].empty?
    assert user.errors[:profile_name].include?("must be formatted correctly")
  end

user.rb (model)

validates :profile_name, presence: true, uniqueness: true, 
format: { with: /a-zA-Z0-9_-/, message: 'must be formatted correctly' }

It raises an error if the profile name has spaces on it, but even if it doesn´t it still raises an error!

2 Answers

I think the problem might be with your validation. The regex you are currently using would only match the string a-zA-Z0-9_-.

Try this:

  validates :profile_name, presence: true, uniqueness: true, 
  format: { with: /\A[a-zA-Z\-\_]+\Z/, message: 'must be formatted correctly' }

Here's a really cool tool if you ever need to see if a regex pattern matches a string.

Jonathan Martínez
Jonathan Martínez
13,375 Points

Thanks for your awesome tip :) I'm not that good with regex hahahaaha.