6

我有一个对象MyObject

class MyObject

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

  def results
   []
  end
end

我只想resultsstat_to_load = "times". 我怎样才能做到这一点?我试过了:

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

但它不起作用。任何想法?

4

3 回答 3

0

在下面尝试,这应该可以按预期工作:

在这里,基本上我们实际上是在对创建的存根以及正在返回的实例的new instance存根方法。results

options = {:stat_to_load =>  "times"}
MyObject.stubs(:new).with(options)
                    .returns(MyObject.new(options).stubs(:results).return(["klala"]))
于 2014-08-19T11:12:57.963 回答
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/

于 2013-05-30T19:07:32.533 回答
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
于 2017-07-16T23:15:04.253 回答