Validations in Rails Models
In this lesson we will walk through how to build specs for and then test validations to ensure data integrity.
Guide Tasks
  • Read Tutorial

In this lesson we will walk through how to build specs for and then test validations to ensure data integrity. If you're new to testing validation specs are some of the most straightforward to build. There's debate on whether or not tests are necessary for validations since they are pretty basic and seem like busy work, however I think it's good practice to have all functionality elements tested in an application.

Opening up the Notification model spec we'll create a new describe block for our validations:

# spec/models/notification_spec.rb

  describe 'validations' do
  end

This will segment our validation specs from any other tests that we write, which is helpful for code organization, and it's also important if you run rspec in documentation mode.

Now let's build a spec that sets all of the values to nil and tell it to expect the notification to not be valid:

# spec/models/notification_spec.rb

  describe 'validations' do
    it 'can be created if valid' do
      notification = FactoryGirl.build_stubbed(:notification)
      notification.phone = nil
      notification.body = nil
      notification.source_app = nil
      expect(notification).to_not be_valid
    end
  end

Running rspec spec/models/notification_spec.rb:11 (side note: this is how you can run the tests for a specific describe block) will give an failure, which is good, so let's implement the validation in the model file.

# app/models/notification.rb

class Notification < ActiveRecord::Base
  validates_presence_of :phone, :body, :source_app
end

Now if you run the spec you'll see that it's passing and if you run rspec to run a regression test you'll see that both specs are now passing, so nice work, notifications now need to be fully filled out in order to be considered valid.

large

This is vital when it comes to building an API based application since there is no way to know what type of data is going to be sent and by integrating validations we can ensure that the database won't have any nil values. Obviously certain apps need to allow for nil values, however for this specific application all the fields should be required.

In the next guide we'll start to build out the functionality that allows for outside applications to create notifications remotely.