ruby-on-rails - 使用 rspec,我可以模拟我正在测试的方法内的对象吗?

标签 ruby-on-rails ruby rspec

我定义了以下方法:

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/

相关文章:

ruby-on-rails - Bootstrap 的 ruby gem 有什么区别?

ruby-on-rails - 用于搜索关键路径的元程序 Squeel

ruby-on-rails - 使用带有 Rspec 的 request-url 的测试 Controller 方法

html - 背景不会显示 : can i put a background upon a back ground in ruby on rails?

rspec - 如何在 puppet-rspec 测试中设置 puppet 环境?

ruby - Rspec 和 bundle exec

ruby-on-rails - 如何使用数组结果在 Rails 上渲染 json ruby

ruby - 无法在 Ruby 的特征类中定义 getter 方法

mysql - 通过事件记录迁移将 rename_column 和 change_column 合二为一

ruby-on-rails - 从 RVM Gemset 中删除 Gem?