Skip to content
This repository was archived by the owner on Jun 11, 2022. It is now read-only.
This repository was archived by the owner on Jun 11, 2022. It is now read-only.

feature: have_attribute value matcher as second argument #13

@Justin-Maxwell

Description

@Justin-Maxwell

Hi.

I've started extending have_attribute to accept an optional RSpec matcher as a second argument, so that flattening logic and such like can be tested. This is my first attempt at forking and extending a gem, so I'm feeling my way through the process somewhat clumsily.

So any tips or advice greatly appreciated - it'll be slow going, so a while before any pull request I expect.

This seems to be basically working though - posting the below incase I'm going about this in drastically the wrong way...

    describe "attributes" do
      let(:author) { Author.new(name: "name") }
      subject(:resource) { AuthorResource.new(author, {}) }
      context 'original without testing attribute value' do
        it { is_expected.to have_attribute(:name) }
        it { is_expected.to_not have_attribute(:created_at) }
      end
      context 'with attribute value tested' do
        it { is_expected.to have_attribute( :name, eq('name')) }
        it { is_expected.to_not have_attribute( :name, eq('fred')) }
        it { is_expected.to have_attribute( :name, start_with('na')) }
        it { is_expected.to_not have_attribute( :name, start_with('fr')) }
        it { is_expected.to have_attribute( :name, match(/a/))  }
        it { is_expected.to_not have_attribute( :name, match(/b/))  }
        it { is_expected.to have_attribute( :name, 'name')  }
        it { is_expected.to_not have_attribute( :name, 'fred')  }
      end
      def have_attribute(name, matcher=nil)
        HaveAttribute.new(name, matcher)
      end
class HaveAttribute      
     attr_accessor :name, :resource, :matcher

        def initialize(name, matcher)
          self.name = name
          self.matcher = matcher
          self.matcher = RSpec::Matchers::BuiltIn::Eq.new(matcher) if matcher && ! defined?(matcher.matches?)
        end
...
          return false unless attributes.has_key?(expected_key)
          @attribute_found= true
          return matcher.nil? || matcher === attributes[expected_key]
        end

        def failure_message
          resource_name = resource.class.name.demodulize
          if @attribute_found
            msg= %Q(#{matcher&.failure_message} for #{resource_name} attribute #{name})
          else
            msg= %Q(expected #{resource_name} to have attribute #{name})
          end
          msg
        end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions