Domanda

I am trying to test a user model, which has the following method(s) that is run after validation:

 def generate_slug(args)
  column = args[:column]
  self.slug = slug_title(column)
 end

private

def slug_text(column)
  self.send(column).gsub(/[^0-9a-z ]/i, '').gsub(' ','-').downcase
end

def slug_number_of_occurences(slug_title)
  self.class.where(slug: slug_title).count
end

def slug_title(column)
  count = 0
  slug_title = slug_text(column)
  until slug_number_of_occurences(slug_title) == 0
    slug_title = slug_text(column) + (count == 0 ? "" : count.to_s)
    count += 1
  end
  return slug_title
end

These methods are causing some of my shoulda matcher tests to fail with the following error:

 ←[31mNoMethodError←[0m:
   ←[31mundefined method `gsub' for nil:NilClass←[0m
m     # ./app/models/concerns/shared/sluggable.rb:18:in `slug_text'←[0m
m     # ./app/models/concerns/shared/sluggable.rb:27:in `slug_title'←[0m
m     # ./app/models/concerns/shared/sluggable.rb:8:in `generate_slug'←[0m
m     # ./app/models/user.rb:10:in `block in <class:User>'←[0m
m     # ./spec/models/user_spec.rb:28:in `block (2 levels) in <top (required)>'←[0m

One example would be:

it { should ensure_length_of(:password).is_at_least(6) }

Is there a way that this error can be bypassed?

È stato utile?

Soluzione

No. The approach used by the shoulda matchers is to assign various values to the column in question and ensure that the validations behave as expected. If your model can't support (i.e. avoid raising an error) for the values used by a particular shoulda matcher, then you need to either change your model to support the values (i.e. not raise an error for a nil password in this case) or stop using that particular shoulda matcher.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top