我定义了以下方法:
def some_method
x = x + 1
y = some_other_method(x)
x + y
end
现在在我的 rspec 规范中,我可以模拟对 some_other_method 的调用以进行 some_method 的单元测试吗?
最佳答案
您确实可以在 RSpec 测试中模拟其他方法。如果您提到的两个方法位于类 Foo
中,您将执行类似以下操作以确保调用 some_other_method
:
subject{ Foo.new }
it "should do whatever you're testing" do
subject.should_receive(:some_other_method).and_return(5)
subject.some_method
end
如果您不需要断言调用,只需断言some_method
的结果,您可以这样做:
subject{ Foo.new }
it "should do whatever you're testing" do
subject.stub(:some_other_method).and_return(5)
subject.some_method.should eq(6)
end
以上示例假设您使用的是 RSpec 2。如果您使用的是 RSpec 1,则需要使用 stub
而不是 stub
。
如果您的方法是在类外部定义的,那么它们实际上是在类 Object
上定义的,因此只需使用 Object
而不是 Foo
> 在上面的例子中。
有关 RSpec 中模拟的更多信息,请查看 http://relishapp.com/rspec/rspec-mocks对于 RSpec 2 或 http://rspec.info/documentation/mocks/对于 RSpec 1。
关于ruby-on-rails - 使用 rspec,我可以模拟我正在测试的方法内的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6207418/