Testing custom validation functions regardless of model in rails application

I am creating a custom validation method for use in my rails application. The type of validator I want to build compares the column in the model, where the validator is called into columns in other tables. Below is an example of code that illustrates the validator pattern that I am trying to create.

module ActiveModel
    module Validations
        module ClassMethods
            # example: validate_a_column_with_regard_to_other_tables :column, tables: { table_one: :some_column }
            def validate_a_column_with_regard_to_other_tables(*attr_names)
                validates_with WithRegardToOtherTablesValidator, _merge_attributes(attr_names)
            end
        end

        class WithRegardToOtherTablesValidator < EachValidator
            def validate_each(record, attribute, value)
                # compare record, attribute or value to all records that match table: :column in :tables
            end
        end
    end
end

You can verify this using the models that exist in the application and schema. However, this is not a good way to test the validator, as it will describe the validator as depending on models that it does not depend on.

The only other way I can think of is to create a set of model layouts in the test.

class ValidateModel < BaseModel
    validate_a_column_with_regard_to_other_tables :column, :tables { compare_to_model: :some_column }
end

class CompareToModel < BaseModel
    attr_accessor :some_column
end

, : column - : some_column in: compare_to_model, : compare_to_model .

, ? , ?

+4
1

rspec, - :

before(:all) do
  ActiveRecord::Migration.create_table :compare_to_model do |t|
    t.string :some_column
    t.timestamps
  end
end

it "validates like it should" do
  ...
end

after(:all) do
  ActiveRecord::Migration.drop_table :compare_to_model
end
  • before(:all) - "" , it , it a before(:each), .
+1

All Articles