2009-12-03
privateのクラスメソッドをスタブにすると、そのメソッドをSpec上で呼び出すときに、undefined method になる
原因は不明
本体
class Test def self.foo var + 'bbb' end def self.var 'aaa' end private_class_method :var end
テスト
require 'test.rb' describe Test do it 'foo' do #Test.should_receive(:var).and_return('ccc') Test.stub!(:var).and_return('ccc') Test.foo.should == 'cccbbb' end it 'var' do Test.send(:var).should == 'aaa' end end
実行結果
spec -c test_spec.rb .F 1) NoMethodError in 'Test var' undefined method `var' for Test:Class ./test_spec.rb:12:in `send' ./test_spec.rb:12: Finished in 0.430245 seconds 2 examples, 1 failure
対策
とりあえず、public にしたら大丈夫だった
なんでだろ???
追記
http://www.ruby-lang.org/ja/man/html/Object.html#send
ruby 1.9 feature: 呼び出し制限がsend, __send__にも影響するようになり、 レシーバを指定した呼び出しではprivateメソッドを呼び出せなくなりました。 privateメソッドを呼び出す必要がある場合はinstance_evalを使用してください。
1.9 から private メソッドを呼べなくなるらしいので、それはそれで注意
追記
ソースの内側まで突っ込んだ話
KoshigoeBLOG: RSpec の stub! とプライベートメソッドの話
トラックバック - http://d.hatena.ne.jp/kasei_san/20091203/p1
リンク元
- 28 http://blog.koshigoe.jp/archives/2009/12/rspec_stub.html
- 5 http://www.google.co.jp/search?q=spec+stub&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:ja:official&hl=ja&client=firefox-a
- 4 http://webcache.googleusercontent.com/search?q=cache:p3ZvtMTr6hoJ:d.hatena.ne.jp/kasei_san/20091021/p1+ruby+include+extend&cd=2&hl=ja&ct=clnk&gl=jp&client=firefox-a&source=www.google.co.jp
- 3 http://www.google.co.jp/search?sourceid=chrome&ie=UTF-8&q=spec+rivate&qscrl=1
- 3 http://www.google.co.jp/url?sa=t&rct=j&q=スタブ private&source=web&cd=1&sqi=2&ved=0CCAQFjAA&url=http://d.hatena.ne.jp/kasei_san/20091203/p1&ei=wc0YT4T_Eu_JmAWDycyNCg&usg=AFQjCNExfq-0zQjvuqG0bi7y82Zqbf-ZGg
- 3 http://www.google.co.jp/url?sa=t&source=web&cd=1&ved=0CBgQFjAA&url=http://d.hatena.ne.jp/kasei_san/20091203/p1&rct=j&q=spec private&ei=U4xrTfDBNMSxcaz14Y4M&usg=AFQjCNExfq-0zQjvuqG0bi7y82Zqbf-ZGg
- 3 http://www.google.com/search?client=safari&rls=en&q=stub+class+method&ie=UTF-8&oe=UTF-8
- 2 http://d.hatena.ne.jp/
- 2 http://reader.livedoor.com/reader/
- 2 http://www.google.co.jp/m?ie=Shift_JIS&q=クラス メソッド スタブ



