Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RobertAudi/dd1486473c3b8549f98667a8959f6311 to your computer and use it in GitHub Desktop.
Save RobertAudi/dd1486473c3b8549f98667a8959f6311 to your computer and use it in GitHub Desktop.
Rspec matcher for attr_accessor, attr_reader and attr_writer
# frozen_string_literal: true
# `have_attr_reader` matcher for attr_reader
RSpec::Matchers.define :have_attr_reader do |field|
match do |object_instance|
object_instance.respond_to?(field)
end
failure_message do |object_instance|
"expected attr_reader for #{field} on #{object_instance}"
end
failure_message_when_negated do |object_instance|
"expected attr_reader for #{field} not to be defined on #{object_instance}"
end
description do
"has attr_reader for #{field} on the #{object_instance.class} instance"
end
end
# `have_attr_writer` matcher for attr_writer
RSpec::Matchers.define :have_attr_writer do |field|
match do |object_instance|
object_instance.respond_to?("#{field}=")
end
failure_message do |object_instance|
"expected attr_writer for #{field} on #{object_instance}"
end
failure_message_when_negated do |object_instance|
"expected attr_writer for #{field} not to be defined on #{object_instance}"
end
description do
"has attr_writer for #{field} on the #{object_instance.class} instance"
end
end
# `have_attr_accessor` matcher for attr_accessor
RSpec::Matchers.define :have_attr_accessor do |field|
match do |object_instance|
object_instance.respond_to?(field) && object_instance.respond_to?("#{field}=")
end
failure_message do |object_instance|
"expected attr_accessor for #{field} on #{object_instance}"
end
failure_message_when_negated do |object_instance|
"expected attr_accessor for #{field} not to be defined on #{object_instance}"
end
description do
"has attr_accessor for #{field} on the #{object_instance.class} instance"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment