0
我有一個教程模型屬於用戶模型。我希望教程標題在每個用戶級別都是唯一的。因此,兩個用戶可以使用相同標題的教程,但用戶不能擁有兩個具有相同標題的教程。我的測試失敗了,但我知道我正在糾正過濾出重複的標題。我的測試出了什麼問題?爲模型名稱唯一性編寫測試
# 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)>'
我將如何重構呢?我應該做'tut.should_not be_valid'嗎?我可以在'@ tutorial'之前創建'tut'嗎? – sunnyrjuneja
增加了一個建議的重構。您可以更改主題,然後正常使用'it {should_not_valid}'。 – wless1