- Read Tutorial
- Watch Guide Video
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
Let's run this test.
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.
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.
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!