Skip to content

Instantly share code, notes, and snippets.

@mendable
Forked from therealadam/accessor_macros.rb
Created August 27, 2009 15:48
Show Gist options
  • Save mendable/176393 to your computer and use it in GitHub Desktop.
Save mendable/176393 to your computer and use it in GitHub Desktop.
# A shoulda macro for verifying a class has the writer attribute readers,
# writers and accessors. NOTE: I could be silly for wanting this. But it was
# there. So here it is.
#
# (c) Copyright 2009 Adam Keys. MIT license.
module AccessorMacros
def should_have_reader(name)
should "have an attribute reader for #{name.to_s}" do
assert ShouldHaveAccessor.new(self, name, :reader).verify?
end
end
def should_have_writer(name)
should "have an attribute writer for #{name.to_s}" do
assert ShouldHaveAccessor.new(self, name, :writer).verify?
end
end
def should_have_accessor(name)
should_have_reader(name)
should_have_writer(name)
end
def should_have_readers(*names)
names.each { |n| should_have_reader(n) }
end
def should_have_writers(*names)
names.each { |n| should_have_writer(n) }
end
def should_have_accessors(*names)
names.each { |n| should_have_accessor(n) }
end
class ShouldHaveAccessor
attr_reader :object, :name, :kind
def initialize(object, name, kind)
@object = object
@name = name
@kind = kind
end
def verify?
selector = case kind
when :reader
name.to_s
when :writer
"#{name.to_s}="
end
subject.respond_to?(selector)
end
def subject
klass_name = object.class.name.gsub(/Test$/, '').downcase
if object.respond_to?(:subject)
object.subject
else
object.instance_variable_get("@#{klass_name}")
end
end
end
end
%w{test/unit rubygems shoulda}.each { |l| require(l) }
class Test::Unit::TestCase
extend AccessorMacros
end
class Gizmo
attr_accessor :foo
attr_reader :bar
attr_writer :baz
attr_reader :one, :two, :three
attr_accessor :oink, :boink
attr_writer :abbott, :costello
end
class GizmoTest < Test::Unit::TestCase
context 'A gizmo' do
setup { @gizmo = Gizmo.new }
should_have_accessor :foo
should_have_reader :bar
should_have_writer :baz
should_have_readers :one, :two, :three
should_have_writers :abbott, :costello
should_have_accessors :oink, :boink
end
end
class HorriblyNamedThingy; attr_accessor :foo; end
class HorriblyNamedClassTest < Test::Unit::TestCase
context 'A class that you would never want to type out' do
setup { @thing = HorriblyNamedThingy.new }
should_have_accessor :foo
end
def subject
@thing
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment