-
Notifications
You must be signed in to change notification settings - Fork 35
Open
Description
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
Metadata
Metadata
Assignees
Labels
No labels