How can I test :inclusion validation in Rails using RSpec

前端 未结 3 1020
终归单人心
终归单人心 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:47

    I found one custom shoulda matcher (in one of the projects I was working on) which attempts to coming close to test something like this:

    Examples:

    it { should validate_inclusion_check_constraint_on :status, :allowed_values => %w(Open Resolved Closed) }
    it { should validate_inclusion_check_constraint_on :age, :allowed_values => 0..100 }
    

    The matcher tries to ensure that there is a DB constraint which blows up when it tries to save it.I will attempt to give the essence of the idea. The matches? implementation does something like:

      begin
        @allowed_values.each do |value|
          @subject.send("#{@attribute}=", value)
          @subject.save(:validate => false)
        end
      rescue ::ActiveRecord::StatementInvalid => e
        # Returns false if the exception message contains a string matching the error throw by SQL db
      end
    

    I guess if we slightly change the above to say @subject.save and let Rails validation blow up, we can return false when the exception string contains something which close matches the real exception error message.

    I know this is far from perfect to contributed back to the project, but I guess might not be a bad idea to add into your project as a custom matcher if you really want to test a lot of the :inclusion validation.

提交回复
热议问题