Search code examples
ruby-on-railsrspecshoulda

Validate_presence_of test passing when it shouldn't?


I just started using RSpec and Shoulda-matchers, and I think something is going wrong here.

In my model, I have a member, displayname, that is validated like this.

validates :displayname, :presence => false #just for this test.

In my spec, i wrote this

it { should validate_presence_of(:displayname) }

Yet it's passing. Shouldn't that fail unless i switch should to should not?

edit: it seems to just be behaving like i said to validate the presence, whether i say true or false. I changed it to should_not and started failing unless i completely removed the presence check. Is the behavior of validates presence to just not use whatever bool you pass it?


Solution

  • Yes, you are right. You can pass any random value to :presence key in the validation. Which means that even if you add any of the following, presence validation is going to take place.

    1. validates :name, :presence => false
    2. validates :name, :presence => true
    3. validates :name, :presence => 'random'
    4. validates :name, :presence => nil

    (Perhaps more readable version of above validation method, validates_presence_of :attr_name, will not cause any such confusion)