sunnyrjuneja
sunnyrjuneja

Reputation: 6123

Writing Tests for Model Name Uniqueness

I'm have a tutorial model which belongs to a user a model. I would like the tutorial titles to be unique on per user level. So two users can have tutorials with the same titles but a user can't have two tutorials with the same title. My test is failing but I know that I'm correcting filtering out titles that are repeated. What is wrong with my test?

# model - tutorial.rb
class Tutorial < ActiveRecord::Base
  attr_accessible :title
  belongs_to :user

  validates :user_id, presence: true
  validates :title, presence: true, length: { maximum: 140 }, uniqueness: { :scope => :user_id }
end

# spec for model
require 'spec_helper'
describe Tutorial do
  let(:user) { FactoryGirl.create(:user) }
  before do
    @tutorial = FactoryGirl.create(:tutorial, user: user)
  end

  subject { @tutorial }

  describe "when a title is repeated" do
    before do
      tutorial_with_same_title = @tutorial.dup
      tutorial_with_same_title.save
    end
    it { should_not be_valid }
  end
end

# rspec output
Failures:
  1) Tutorial when a title is repeated 
     Failure/Error: it { should_not be_valid }
       expected valid? to return false, got true
     # ./spec/models/tutorial_spec.rb:50:in `block (3 levels) in <top (required)>'

Upvotes: 0

Views: 92

Answers (1)

wless1
wless1

Reputation: 3549

The problem with the test is this line:

it { should_not be_valid }

This spec checks valid? on the subject of your test, which is @tutorial - which is valid.

Suggested Refactoring:

describe Tutorial do
  let(:user) { FactoryGirl.create(:user) }
  before do
    @tutorial = FactoryGirl.create(:tutorial, user: user)
  end

  subject { @tutorial }

  describe "when a title is repeated" do
    subject { @tutorial.dup }
    it { should_not be_valid }
  end
end

Upvotes: 1

Related Questions