gpt4 book ai didi

ruby-on-rails - 仅当特定实例变量具有值时,如何 stub 实例方法?

转载 作者:数据小太阳 更新时间:2023-10-29 07:08:31 25 4
gpt4 key购买 nike

我有一个对象MyObject:

class MyObject

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

def results
[]
end
end

仅当 stat_to_load = "times" 时,我才想 stub results 方法。我怎样才能做到这一点?我试过了:

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

但它不起作用。有什么想法吗?

最佳答案

因此,我认为可能有一种更简单的方法来测试您要测试的内容,但如果没有更多上下文,我不知道该推荐什么。但是,这里有一些概念验证代码可以表明您可以完成您想要做的事情:

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

不过,我在这里大量使用了特殊的主题/让上下文 block 。参见 http://benscheirman.com/2011/05/dry-up-your-rspec-files-with-subject-let-blocks/有关该主题的更多信息。

关于ruby-on-rails - 仅当特定实例变量具有值时,如何 stub 实例方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16815985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com