2013-05-29 10 views
6

私はオブジェクトMyObject持っている:特定のインスタンス変数に値がある場合にのみ、インスタンスのメソッドをスタブするにはどうすればよいですか?

class MyObject 

    def initialize(options = {}) 
    @stat_to_load = options[:stat_to_load] || 'test' 
    end 

    def results 
    [] 
    end 
end 

を私はstat_to_load = "times"場合resultsメソッドをスタブにしたいです。どうやってやるの?試しました:

MyObject.any_instance.stubs(:initialize).with({ 
    :stat_to_load => "times" 
}).stubs(:results).returns(["klala"]) 

ただし、動作しません。何か案が?

+1

質問で「結果」と「結果」の不一致が確認できます。おそらく答えはありませんが、修正する価値はありますか? –

+0

Oups、コピー/ペーストエラー – Sebastien

+0

これが可能かどうかはわかりませんが、オブジェクトやクラスを注入するのが正しい解決策である可能性があります。このコードがどのように使用されているかを見ずに例を挙げたり発言するのは難しいです。 –

答えて

0

私はおそらく、テストしようとしているものをテストするためのより簡単な方法があると思いますが、それ以上のコンテキストがなければ何を推奨するのか分かりません。

describe "test" do 
    class TestClass 
    attr_accessor :opts 
    def initialize(opts={}) 
     @opts = opts 
    end 

    def bar 
     [] 
    end 
    end 
    let!(:stubbed) do 
    TestClass.new(args).tap{|obj| obj.stub(:bar).and_return("bar")} 
    end 
    let!(:unstubbed) { TestClass.new(args) } 

    before :each do 
    TestClass.stub(:new) do |args| 
     case args 
     when { :foo => "foo" } 
     stubbed 
     else 
     unstubbed 
     end 
    end 
    end 

    subject { TestClass.new(args) } 

    context "special arguments" do 
    let(:args) { { :foo => "foo" } } 
    its(:bar) { should eq "bar" } 
    its(:opts) { should eq({ :foo => "foo" }) } 
    end 

    context "no special arguments" do 
    let(:args) { { :baz => "baz" } } 
    its(:bar) { should eq [] } 
    its(:opts) { should eq({ :baz => "baz" }) } 
    end 

end 

test 
    special arguments 
    bar 
     should == bar 
    opts 
     should == {:foo=>"foo"} 
    no special arguments 
    bar 
     should == [] 
    opts 
     should == {:baz=>"baz"} 

Finished in 0.01117 seconds 
4 examples, 0 failures 

しかし、私は特別な主題の使用の多くを作っている/してみましょう。ただし、ここにあなたが何をしたいかに行うことができることを示すために、いくつかの概念実証コードがありますコンテキストブロックはここにあります。その件については、http://benscheirman.com/2011/05/dry-up-your-rspec-files-with-subject-let-blocks/を参照してください。

+0

この回答はRSpecではないmocha –

0

は予想通り、これは動作するはずです、以下試してみてください:ここで

、基本的に私たちが実際にnew instanceが作成取得スタブとも返さなっているインスタンスのresults方法をスタブされています。

options = {:stat_to_load => "times"} 
MyObject.stubs(:new).with(options) 
        .returns(MyObject.new(options).stubs(:results).return(["klala"])) 
0

これを実現するには、テストの中で単純な古いRubyを使用できます。

MyObject.class_eval do 
    alias_method :original_results, :results 
    define_method(:results?) do 
    if stats_to_load == "times" 
     ["klala"] 
    else 
     original_results 
    end 
    end 
end