How to remove validation using instance_eval clause in Rails?

后端 未结 18 1794
情话喂你
情话喂你 2021-02-01 02:11

I would like to enhance existing class using instance_eval. There original definition contains validation, which require presence of certain fields, ie:

class Du         


        
18条回答
  •  隐瞒了意图╮
    2021-02-01 02:55

    Every Rails validator, pre-defined or custom, is an object, and is expected to respond to #validate(record) method. You can monkey patch or stub this method.

    # MyModel.validators_on(:attr1, :attr2, ...) is also useful
    validator = MyModel.validators.detect do |v|
      validator_i_am_looking_for?(v)
    end
    
    def validator.validate(*_)
      true
    end
    
    # In RSpec you can also consider:
    allow(validator).to receive(:validate).and_return(true)
    

    Tested in Rails 5.1.

    Don't do this unless you understand what you're doing ;)

提交回复
热议问题