Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom Matcher's #29

Open
fluxsaas opened this issue Aug 19, 2014 · 1 comment
Open

Custom Matcher's #29

fluxsaas opened this issue Aug 19, 2014 · 1 comment

Comments

@fluxsaas
Copy link

Hey,

i was a bit confused on how to create custom matchers, so i wanted to share a solution. You can include the module in rspec/others and use it:

show action e.g.:

response.body.should match_json_expression(JSONPatterns.user)

index action e.g.:

response.body.should match_json_expression(JSONPatterns.users(User.count))
# spec/support/json_patterns.rb
module JSONPatterns

  class ValidDateMatcher
    def ==(other)
      return DateTime.parse other rescue nil
    end
  end

  class NilOrIntegerMatcher
    def ==(other)
      other.nil? || other.is_a?(Integer)
    end
  end

  class NilOrStringMatcher
    def ==(other)
      other.nil? || other.is_a?(String)
    end
  end

  class << self

    def valid_date
      @DATE_MATCHER ||= ValidDateMatcher.new
    end

    def nil_or_integer
      @NIL_OR_INTEGER_MATCHER ||= NilOrIntegerMatcher.new
    end

    def nil_or_string
      @NIL_OR_STRING_MATCHER ||= NilOrStringMatcher.new
    end

    def user
      {
        id: Integer,
        created_at: valid_date,
        updated_at: valid_date,
        name: String,
        avatar: nil_or_string
      }
    end

    def users n
      [user] * n
    end

  end

end
@MiroslavCsonka
Copy link
Collaborator

Hi,

thanks very much for your example with NilOrStringMatcher I also got stuck with it. I played with little something and I would love to hear and opinion from someone else.

I liked your JSONPatterns but also sometimes I want to make sure, that some attributes (usually ids are correct) so I extended it a bit
https://gist.github.com/MiroslavCsonka/6919b62c222bf76ba13f

Let me please know what you think. If it makes sense I could udpate README with some examples

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants