编写模型名称唯一性的测试

时间:2013-01-18 23:25:40

标签: ruby-on-rails rspec

我有一个属于用户模型的教程模型。我希望教程标题在每个用户级别上是唯一的。因此,两个用户可以拥有相同标题的教程,但用户不能拥有两个具有相同标题的教程。我的测试失败但我知道我正在纠正过滤掉重复的标题。我的考试有什么问题?

# 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)>'

1 个答案:

答案 0 :(得分:1)

测试的问题是这一行:

it { should_not be_valid }

此规范检查valid?您测试的主题,@tutorial - 这是有效的。

建议的重构:

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