Test Models

Write effective tests for your CQL Active Record models.

Prerequisites

  • CQL application with models

  • Crystal spec testing framework

  • Test database configured

Basic Model Tests

require "spec"
require "../src/models/*"

describe User do
  describe "#valid?" do
    it "is valid with valid attributes" do
      user = User.new("John", "john@example.com")
      user.valid?.should be_true
    end

    it "is invalid without email" do
      user = User.new("John", "")
      user.valid?.should be_false
    end

    it "is invalid with malformed email" do
      user = User.new("John", "invalid-email")
      user.valid?.should be_false
    end
  end
end

Testing Persistence

Testing Callbacks

Testing Relationships

Testing Scopes

Test Helpers

Create helpers for common operations:

Factory Pattern

Database Cleanup

Clean up between tests:

Running Tests

See Also

Last updated

Was this helpful?