Shoulda-matchers: Before_validation callback with shoulda matchers

Created on 14 Jun 2015  路  1Comment  路  Source: thoughtbot/shoulda-matchers

Hello,

I have been experiencing a problem that has been frustrating me for a quite a while now.

So basically to replicate a problem,
let's say there is a model named "Food", with attribute "Name" and "Clean Name".

I use before_validation to call a method that strips 'name' of all the unnecessary / unwanted characters and set the 'clean_name' attirubte.

Then, I can run validate_uniqueness_of :clean_name.

However, the before_validation callback gets called for every shoulda matchers such as should allow_value, and it causes a undefined method nil:nilclass for all of them (I'm assuming since the name attribute is blank), breaking a huge number of tests.

Is there a way to get around this problem with before_validation callback + shoulda matcher?

Thanks for any input

Most helpful comment

Hi @innhyu,

Sorry this is so late -- I must have completely missed this.

You might have already figured this out, but your before_validation callback needs to take into account the possibility that name could be nil (as this is a real possibility, both when using matchers in tests and in real life). So, you'd probably want something like:

before_validation :set_clean_name

private

def set_clean_name
  if name.present?
    self.clean_name = clean_name_somehow(name)
  end
end

Hope that helps!

>All comments

Hi @innhyu,

Sorry this is so late -- I must have completely missed this.

You might have already figured this out, but your before_validation callback needs to take into account the possibility that name could be nil (as this is a real possibility, both when using matchers in tests and in real life). So, you'd probably want something like:

before_validation :set_clean_name

private

def set_clean_name
  if name.present?
    self.clean_name = clean_name_somehow(name)
  end
end

Hope that helps!

Was this page helpful?
0 / 5 - 0 ratings