2

In my rails project I have a model with attribute foo. I have a vaildation which ensures that any value for foo is in an array. This uses a validation with the :in option.

I want to test this using rspec/shoulda. I think ensure_inclusion_of is supposed to test this validation but it only works on ranges and not an array. How can I make it work with an array or write my own matcher to do this?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Zameer Manji
  • 3,017
  • 5
  • 31
  • 42

2 Answers2

4

ensure_inclusion_of is for checking whether Modules are included in the current class.

If you wish to test validates_inclusion_of you can either write RSpecs for this yourself, or install the Shoulda and use it's macros.

Here I validate the gender field on a user model.

describe User do

  it { should validate_presence_of(:gender) }
  it { should allow_value("male").for(:gender) }
  it { should allow_value("female").for(:gender) }
  it { should_not allow_value("other").for(:gender) }

end
Douglas F Shearer
  • 25,952
  • 2
  • 48
  • 48
3

You can now write it like this:

it { should ensure_inclusion_of(:gender).in_array(%w(male female)) }
PhilT
  • 4,166
  • 1
  • 36
  • 26