How can I test :inclusion validation in Rails using RSpec

前端 未结 3 1024
终归单人心
终归单人心 2021-01-31 15:14

I have the following validation in my ActiveRecord.

validates :active, :inclusion => {:in => [\'Y\', \'N\']}

I am using the following to

3条回答
  •  逝去的感伤
    2021-01-31 15:54

    If you have more elements to test than a boolean Y/N then you could also try.

    it "should allow valid values" do
      %w(item1 item2 item3 item4).each do |v|
        should allow_value(v).for(:field)
      end
    end
    it { should_not allow_value("other").for(:role) }
    

    You can also replace the %w() with a constant you have defined in your model so that it tests that only the constant values are allowed.

    CONSTANT = %w[item1 item2 item3 item4]
    validates :field, :inclusion => CONSTANT
    

    Then the test:

    it "should allow valid values" do
      Model::CONSTANT.each do |v|
        should allow_value(v).for(:field)
      end
    end
    

提交回复
热议问题