Search⌘ K
AI Features

Unit Test: Maximum Length Constraint

Understand how to define and pass a unit test that restricts the name field to 100 characters in a Rails model. Learn the process of starting with the test, interpreting test failures, and implementing model validations to meet requirements.

We'll cover the following...

Defining the test

This test’s goal is to disallow more than 100 characters in the name field. Notice how we’re starting with the test. We’re describing the behavior we’d like to have, and only then do we implement it

Put the following test in the spec/models/user_spec.rb file.

Ruby
require 'rails_helper'
RSpec.describe User, type: :model do
describe "validations" do
context "when the name is longer than 100 characters" do
it "the record is invalid" do
user = User.new(name: "a" * 101)
user.valid?
expect(user.errors.messages).to include(:name)
end
end
end
end

Add the test to the widget below and run the test.

Note: You need to add the code above to the SPA.

--require spec_helper
Setting up the maximum length constraint test

We get the following failure.

Failure/Error: expect(user.errors.messages).to include(:name)

  expected {:email => ["can't be blank"], :password => ["can't be blank"]} to include :name
  Diff:
  @@ -1,2 +1,3 @@
  -[:name]

This tells us that the test expected an error for the name field but found errors for email and password instead. That’s okay.

The Devise gem sets the email and password validations, and we don’t care about those fields in our current test.

In other words, the test is correct. It fails for the right reason. Now, let’s write the implementation that makes it pass.

Passing the test

To pass the test, we’ll add the following line to our User model:

Ruby
validates :name, length: { maximum: 100 }

That’s it! The first test should pass now.

--require spec_helper
Passing the maximum length constraint test