first_nameとlast_nameのいずれかが空でない場合にのみ、RoRモデルで検証を設定して渡す必要があります。これは、最初の2つのテスト 2つの値から1つの値を検証する必要があります!= nil
context "Validators:" do
it "does not allow a User without a username" do
expect(User.new(:username=> "")).to_not be_valid
end
it "does not allow a Profile with a null first and last name" do
expect(Profile.new(:first_name=>nil, :last_name=>nil, :gender=>"male")).to_not be_valid
end
end
しかし、次のテストに合格だとすると、エラーメッセージに
it "allows a Profile with a null first name when last name present" do
expect(Profile.new(:first_name=>nil, :last_name=>"Smith", :gender=>"male")).to be_valid
end
モデル
class Profile < ActiveRecord::Base
belongs_to :user
validates :gender, inclusion: {in: %w(male, female), message: "Must be male or female"}
validate :first_or_last_name
def first_or_last_name
if first_name && last_name == nil
errors.add(:first_name, "Cannot be both nil")
end
end
end
1) Assignment rq11 Validators: allows a Profile with a null first name when last name present
Failure/Error: expect(Profile.new(:first_name=>nil, :last_name=>"Smith", :gender=>"male")).to be_valid
expected `#<Profile id: nil, gender: "male", birth_year: nil, first_name: nil, last_name: "Smith", user_id: nil, created_at: nil, updated_at: nil>.valid?` to return true, got false
# ./spec/assignment_spec.rb:290:in `block (4 levels) in <top (required)>'
# ./spec/assignment_spec.rb:12:in `block (2 levels) in <top (required)>'
スペックを取得します
論理演算子に問題はありますか?
上記のすべてをチェックしてください。それでも同じエラー。他のどこかに問題があるはずです –
'validate:first_or_last_name'をコメントアウトすると、仕様は合格しますか? –
しかし、それは解決策に私を導いた。ジェンダーバリデーターはそれを許可しません。 –