Module: RSpec::ValidatorSpecHelper

Defined in:
lib/rspec/validator_spec_helper.rb,
lib/rspec/validator_spec_helper/version.rb

Constant Summary collapse

ATTRIBUTE_NAME =
:value
VERSION =
"1.0.0"

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/rspec/validator_spec_helper.rb', line 10

def self.included(base)
  base.instance_eval do
    let(:validator_name) do |example|
      example.full_description.match(/\A\w+Validator/)[0]
    end

    let(:validator_class) { Object.const_get(validator_name) }

    let(:validator_type) do
      if validator_class.ancestors.include? ActiveModel::EachValidator
        ActiveModel::EachValidator
      else
        ActiveModel::Validator
      end
    end

    let(:validation_name) do
      validator_name.underscore.gsub(/_validator\Z/, '')
    end

    let(:attribute_names) { [ATTRIBUTE_NAME] }

    let(ATTRIBUTE_NAME) { nil }

    let(:options) { nil }

    let(:model_class) do
      example_group = self
      Struct.new(*attribute_names) do
        include ActiveModel::Validations

        def self.name
          'DummyModel'
        end

        if example_group.validator_type == ActiveModel::EachValidator
          args = { :"#{example_group.validation_name}" => (example_group.options || true) }
          validates ATTRIBUTE_NAME, args
        else
          if example_group.options.nil?
            validates_with example_group.validator_class
          else
            validates_with example_group.validator_class, example_group.options
          end
        end
      end
    end

    subject do
      attributes = attribute_names.map { |name| eval("#{name}") }
      model_class.new(*attributes)
    end
  end
end