Created
January 6, 2012 14:08
-
-
Save yuroyoro/1570769 to your computer and use it in GitHub Desktop.
rspecのlet(:name)で定義したオブジェクトのto_sとinspectの値を、:nameに変更する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# rspecのlet(:name)で定義したオブジェクトのto_sとinspectの値を、:nameに変更する | |
# | |
# named_let(:foo){ Object.new } ってやると、 | |
# foo.to_sが"foo"になる | |
# | |
# named_let(:foo,"label for display"){ ... } って第二引数に別名を渡すと、 | |
# その別名が、to_s/inspectの値になる | |
# | |
# subject should == fooとか書いたときの出力が | |
# ふつうは | |
# should == #<Object:0x2aaaaf8a0870> | |
# とかで汚いけど、これをつかうと | |
# should == "label for display" | |
# のようにキレイになる | |
# In RSpec 2.8, RSpec::Core::Let::ExampleGroupMethods | |
if RSpec::Core::Version::STRING < "2.8.0" | |
klass = RSpec::Core::Let::ClassMethods | |
else | |
klass = RSpec::Core::Let::ExampleGroupMethods | |
end | |
klass.class_eval do | |
def named_let(name, label = nil, &block) | |
define_method(name) do | |
__memoized.fetch(name) {|k| __memoized[k] = instance_eval(&block).tap{|o| | |
the_name = label || name | |
to_s_code = "def to_s; \"#{the_name}\" end" | |
inspect_code = "def inspect; \"#{the_name}\" end" | |
begin | |
o.instance_eval <<-CODE | |
def to_s; "#{the_name}" end | |
def inspect; "#{the_name}" end | |
CODE | |
rescue TypeError | |
o | |
end | |
} } | |
end | |
end | |
def named_let!(name, label = nil, &block) | |
named_let(name, label, &block) | |
before { __send__(name) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment