Adding ActiveRecord Uniqueness Validations to the Client Class
This guide explains how to implement ActiveRecord validations to a microservice client class using TDD.
Guide Tasks
  • Read Tutorial

This is probably all second nature for you now, so let's run through what we need to do:

  1. Create tests for data integrity
  2. Implement ActiveRecord validations

Remember that the source_app value is being used as our foreign key connecting the tables. Therefore it's absolutely vital that we ensure our data validations are comprehensive.

We already have validations to ensure that source_app and api_key are required, so we only have one more validation to implement to ensure that both elements are unique. We can't have any applications that have duplicate values since that would cause authorization conflicts, especially with our source_app foreign key.

# spec/models/client_spec.rb

    it 'has a unique source_app' do
      first_client = Client.create(source_app: "app_name", api_key: "I384fHtD1h9XZvs4fGPJUgtt")
      duplicate_client = Client.create(source_app: "app_name", api_key: "I384fHtD1h9XZvs4fGPJUgtt")
      expect(duplicate_client).to_not be_valid
    end

Notice for this that I'm using the create method to build new clients. This is because I want to touch the database with this specific test. It's slightly slower but it's a better way to test uniqueness validations. I'm also not using any factories for this so that I can have both potential clients in front of me.

If you run the code now you'll see that it fails as expected.

large

The code to implement this validation is very similar to what we added to ensure that the values exist. Let's update the model file and add in a call to the validates_uniqueness_of validation method.

# app/models/client.rb

class Client < ActiveRecord::Base
  has_many :notifications, foreign_key: 'source_app', primary_key: 'source_app'
  validates_presence_of :source_app, :api_key
  validates_uniqueness_of :source_app, :api_key
end

Now if you run the tests you'll see that they're passing and we can now be confident that no clients can be created with duplicate values.

large

What's Next?

Next we're going to build the api_key generator that will create a new key each time a client is created.

Resources