Search⌘ K
AI Features

Unit Test: Minimum Length Constraint

Understand how to create unit tests for minimum length constraints on model attributes in Rails. Learn to write tests that initially fail, implement validations, and handle optional fields using allow_nil to ensure all tests pass consistently.

We'll cover the following...

Defining the test

This test concerns the minimum length of the name field. We want the minimum length to be two characters. We’ll start with the behavior we wish we had.

Ruby
context "when the name is less than 2 characters" do
it "the user is invalid" do
user = User.new(name: "a")
user.valid?
expect(user.errors.messages).to include(:name)
end
end

It sets a value that’s too short for the name field and it expects it to fail.

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