Rails 3 validate_presence_of if/unless => Proc?

306 views
Skip to first unread message

ericindc

unread,
Aug 19, 2010, 11:18:18 PM8/19/10
to Remarkable
I have a validation in Rails 3 that is unexpectedly failing. Can
anyone shed some light? I don't see mention of if/unless in the
documentation for validate_presence_of, so how would I test the
following?

validates :mobile_carrier, :presence => true, :if => Proc.new {|v|
v.mobile_phone.present?}


----------------


it { should validate_presence_of(:mobile_carrier, :if => Proc.new {|v|
v.mobile_phone.present?})}

Ho-Sheng Hsiao

unread,
Aug 20, 2010, 5:47:43 PM8/20/10
to Remarkable

You would do something like this:

describe MyModel
context "when mobile phone is present" do
subject { MyModel.new(:mobile_phone => true) }
it { should validate_presence_of :mobile_carrier }
end

context "when mobile phone is not present" do
subject { MyModel.new(:mobile_phone => false) }
it { should_not validate_presence_of :mobile_carrier }
end
end

I haven't tried this and I don't remember if the should_not works on
the validates_* properly.

I've always been partial to the way Datamapper handles things with
contextual validations.

You can get more sophisticated if you use the let() feature in Rspec.

Hope this helps.

Ho-Sheng Hsiao
Reply all
Reply to author
Forward
0 new messages