我对 Rspec 测试相当陌生,这非常令人沮丧。
我有一个模型,它使用validates_uniqueness_of来防止创建重复条目。(我知道这不能保证,首选方法是使用数据库级别的约束,但目前不相关)。
问题是我的 Rspec 测试似乎表明可以在表中创建 2 个具有相同 user_id 和 board_id 的条目,即使在实践中,在控制台和应用程序本身中,这无法完成。
模型/主持人_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)>'