Question

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?

Was it helpful?

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)

OTHER TIPS

The validates_presence_of matcher in shoulda-matchers does not do a verification of the field to see if it has a value. It only verifies that the model has a validation for the presence of the attribute declared on it. If you're concerned about whether or not the validation actually works, you'll need more tests for that.

This is why the test starts to fail when you change your assertion from should to should_not.

I guess your test database are not reflecting the actual schema. Make sure you have update your test database every time you run a migration that changes your db.

rake db:test:prepare

Also, if you are running spork, make sure you have stopped it and started it again to reload all the stuff.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top