我有一个对象MyObject
:
class MyObject
def initialize(options = {})
@stat_to_load = options[:stat_to_load] || 'test'
end
def results
[]
end
end
我想仅在results
时存根stat_to_load = "times"
方法。我怎样才能做到这一点?我试过了:
MyObject.any_instance.stubs(:initialize).with({
:stat_to_load => "times"
}).stubs(:results).returns(["klala"])
但它不起作用。有什么想法吗?
答案 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
但是我在这里大量使用了特殊主题/ let上下文块。有关该主题的更多信息,请参阅http://benscheirman.com/2011/05/dry-up-your-rspec-files-with-subject-let-blocks/。
答案 1 :(得分:0)
尝试下面,这应该按预期工作:
在这里,基本上我们实际上正在创建new instance
被创建,并且还会返回返回的实例的results
方法。
options = {:stat_to_load => "times"}
MyObject.stubs(:new).with(options)
.returns(MyObject.new(options).stubs(:results).return(["klala"]))
答案 2 :(得分: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