How to Write RSpec Validation Tests Part 2 of 2
In this lesson we're going to continue building out the validation tests for our User model using the RSpec testing framework in a Ruby on Rails application, using TDD principles to guide our development.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this lesson we're going to continue building out the validation tests for our User model using the RSpec testing framework in a Ruby on Rails application, using BDD principles to guide our development.

Let's first do the length validations, and the code for that is:

describe "length validations" do
  it "should not allow a name longer than 50 characters" do
    @user.name = "j" * 51
    expect(@user).to_not be_valid 
  end
end

large

Let's run this test.

large

If you see, we have three cases that passed and one that failed. This is the way we want it.

To get this test to pass, go to your user.rb file and add the validation code, which is:

validates_length_of :name, :maximum => 50

Let's run this test again and see if it works.

large

Everything looks good.

So, this is just a quick demo on how to get started with RSpec. If you want to know more, feel free to join the RSpec class where we'll be building some complex things, with tests driving the development for us.

The last thing we're going to see is the documentation format. Though the tests gave us the information we wanted, it's not really well-formatted. To have a cleaner documentation, you can use this option,

bundle exec rspec --format documentation

This is how your information gets displayed when you use this option.

large

This gives a more explicit explanation of why we created each of the describe blocks.

That's the end of this section on implementing RSpec tests into the Rails application, and I hope you had fun!