我的答案模型上有 2 个范围唯一性验证,我正在尝试使用 Rspec 和相应的 shoulda 匹配器来测试这些验证。
如下所示test trace
,唯一性验证消息存在于错误数组中,但是,也存在 2 个,有时是 3 个其他错误;"body can't be blank (nil)", "body is too short (minimum is 10 characters) (nil)", "user_id can't be blank (nil)"
. 我不确定它们来自哪里,因为 body 和 user 属性是在 before 块中明确设置的。
如何纠正这些额外的错误,以便通过唯一性测试?
答案.rb
validates_uniqueness_of :correct, scope: :question_id, if: :correct?, message: "You can only have 1 correct answer per question"
validates_uniqueness_of :user_id, scope: :question_id, message: "Only 1 answer per question per user"
/* omitted for brevity */
answer_spec.rb
require "spec_helper"
describe Answer do
before(:each) do
@user1 = create(:user)
@answer = create(:answer, correct: true, user_id: @user1.id, body: "some text which is over 10 chars long")
end
subject { @answer }
it { should respond_to(:user_id) }
it { should respond_to(:question_id) }
it { should respond_to(:body) }
it { should respond_to(:correct)}
it { should respond_to(:votes_count)}
it { should respond_to(:points)}
it { should belong_to(:question)}
it { should belong_to(:user)}
it { should have_many(:activities)}
it { should have_many(:comments)}
it { should have_many(:votes)}
it { should validate_uniqueness_of(:correct).scoped_to(:question_id).with_message("correct You can only have 1 correct answer per question (true)") }
it { should validate_uniqueness_of(:user_id).scoped_to(:question_id).with_message("user_id Only 1 answer per question per user (1)") }
/* omitted for brevity */
测试轨迹
1) Answer
Failure/Error: it { should validate_uniqueness_of(:correct).scoped_to(:question_id).with_message("correct You can only have 1 correct answer per question (true)") }
Expected errors to include "correct You can only have 1 correct answer per question (true)" when correct is set to true, got errors: ["body can't be blank (nil)", "body is too short (minimum is 10 characters) (nil)", "user_id can't be blank (nil)", "correct You can only have 1 correct answer per question (true)"]
# ./spec/models/answer_spec.rb:20:in `block (2 levels) in <top (required)>'
2) Answer
Failure/Error: it { should validate_uniqueness_of(:user_id).scoped_to(:question_id).with_message("user_id Only 1 answer per question per user (1)") }
Expected errors to include "user_id Only 1 answer per question per user (1)" when user_id is set to 1, got errors: ["body can't be blank (nil)", "body is too short (minimum is 10 characters) (nil)", "user_id Only 1 answer per question per user (1)"]
# ./spec/models/answer_spec.rb:21:in `block (2 levels) in <top (required)>'
Finished in 1.31 seconds
17 examples, 2 failures
工厂.rb
factory :answer do
user
question_id :question
body "you need to change your grip"
votes_count 0
correct false
end