简体   繁体   中英

How does this length validation work in Ruby on Rails?

I am following the Rails tutorial by Michael Hartl. In chapter 6 we're creating a length validation test for a users name and email.

In the test/models/user_test.rb file he says to write

test "name should not be too long" do
@user.name = "a" * 51
assert_not @user.valid? 
end

and then in app/models/user.rb we put

class User < ActiveRecord::Base 
validates :name,  presence: true, length: { maximum: 50 }

My question is, how does the test ensure that the name is not, for example, 60 characters long? I get that the validation says to make the max length 50, but the test says assert that the user is not valid if user.name EQUALS 51 characters...not greater than or equal to.

To be completely honest, I don't understand the relationship between why you need the validates in user.rb and then also the test file, so that could be why I'm confused.

In tests, you need to ensure that your code does everything as you expect. In this case that you can't save the user with name which is longer than 50 symbols. Thats why in test you are checking that user becomes invalid with name length == 51 symbol.

But you are also correct that this test doesn't guarantee that user with name length 60 will be invalid too. It also doesn't check that 50 is the maximum, because it will pass for

validates :name,  presence: true, length: { maximum: 1 }

for example. But you probably don't want your app to behave like this. That's why I also encourage you to add another check for maximum allowed length:

@user.name = "a" * 50
assert @user.valid?

Usually, if you are doubt that something can be wrong in your code, you are free to add new tests. But in this case, you shouldn't actually test how the code behaves, because presence/length validations are well-tested in Rails itself. You should just check that you included such validations in your model with correct arguments passed. For example, in shoulda-matchers you have these helpers:

should validate_presence_of(:name)
should validate_length_of(:name).is_at_most(50)

I am not sure if unit-test have the analogs, most likely no, so you should test it yourself in the way you do this and assume this is enough.

The test is just asserting that a user name with 51 characters should not be a valid one.

The test doesn't 'ensure' that the user name can't be 60 characters long. That's what the actual validation code does.

For example, if you were to change the validation code to this:

class User < ActiveRecord::Base 
validates :name,  presence: true, length: { maximum: 60 }

then the test would fail because the code is validating a user name with 51 characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM