我對Rspec測試相當陌生,這非常令人沮喪。當它失敗時,validates_uniqueness_of的Rspec測試通過
我有一個模型,它使用validates_uniqueness_of來防止重複條目被創建。 (我知道這是不能保證的,首選的方法是使用數據庫級別的約束,但目前不相關)。
問題是,我的Rspec測試似乎表明,即使在實踐中,在控制檯和應用程序本身中,這也無法完成,但可以在表中創建2個具有相同user_id和board_id的條目。
型號/ moderator_join.rb
class ModeratorJoin < ActiveRecord::Base
belongs_to :user
belongs_to :board
validates :user_id, presence: true
validates :board_id, presence: true
validates_uniqueness_of :user_id, scope: :board_id, message: "is already a moderator of that board."
end
規格/型號/ moderator_join_spec.rb
describe ModeratorJoin do
let(:user) { create(:user) } // Create with FactoryGirl
let(:board) { create(:board) } // Create with FactoryGirl
let(:join) { ModeratorJoin.create(user: user, board: board) }
subject { join }
it { should be_valid } // Test passes
its(:id) { should_not eq nil } // Test passes
its(:user) { should eq user } // Test passes
its(:board) { should eq board } // Test passes
describe "user/board pairs" do
let(:join2) { ModeratorJoin.new(user: user, board: board) }
it "must be unique" do
expect(join2).to_not be_valid // TEST FAILS
end
end
end
控制檯輸出
Failures:
1) ModeratorJoin user/board pairs must be unique
Failure/Error: expect(join2).to_not be_valid
expected #<ModeratorJoin id: nil, user_id: 121, board_id: 1, created_at: nil, updated_at: nil> not to be valid
# ./spec/models/moderator_join_spec.rb:39:in `block (3 levels) in <top (required)>'
你說它通過時,它應該失敗,但你顯示失敗? – 2014-10-06 18:43:25