2016-08-01 4 views
0
私は他の多くの、次の要件の中で、持っている割り当てに取り組んでいます

カスタムレールバリデータではないの両方

Define custom validator that permits first_name or last_name to be null but not both 

私は働く何かを持っているが、私

def at_least_one_name 
    if first_name.nil? && last_name.nil? 
    errors.add(:first_name, "Must contain at least a first or last name") 
    end 
end 

これを完全にテストする方法はわかりません。私が上に持っているのは、両方が無ければテストすることだけです。私がエラー配列に:first_nameを追加しているという事実は、すでに何かが間違っていることを私に伝えています。

これはif/elseでしょうか?それらは検証で動作しますか?

編集:私はパスを作成しようとしているテスト:あなたのケースでは

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 
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 
it "allows a Profile with a null last name when first name present" do 
    expect(Profile.new(:first_name=>"Joe", :last_name=>nil, :gender=>"male")).to be_valid 
end 
+0

あなたが役に立った場合は、答えをマークする必要があります。 – Nickey

答えて

0

あなたが&&演算子を使用しています。両方のチェック。その代わりに||を試してみてください。以下のように変更してください。

def at_least_one_name 
    if first_name.present? || last_name.present? 
    errors.add(:first_name, "Must contain at least a first or last name") 
    end 
end 

も、このような他の方法があります。

Dipak G.によって提供される情報を用いて、
validates :first_name, presence: true, unless: ->(user){user.last_name.present?} 
validates :last_name, presence: true, unless: ->(user){user.first_name.present?} 
0

私は解決策に来ることができました:

def at_least_one_name 
    unless first_name.present? || last_name.present? 
    errors.add(:user, "Must contain at least a first or last name" 
    end 
end 

これは動作しません他のテストを中断する。

関連する問題