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 =
"0.0.1"

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



7
8
9
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
# File 'lib/rspec/validator_spec_helper.rb', line 7

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(: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
          validates ATTRIBUTE_NAME, :"#{example_group.validation_name}" => true
        else
          validates_with example_group.validator_class
        end
      end
    end

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