我是模拟对象的新手,我正在努力学习如何在RSpec中使用它们.有人可以发布一个示例(hello RSpec Mock object world类型示例)或一个关于如何使用RSpec Mock object API的链接(或任何其他参考)吗?

推荐答案

下面是我在rails应用程序中为控制器测试所做的一个简单模拟示例:

before(:each) do
  @page = mock_model(Page)
  @page.stub!(:path)
  @page.stub!(:find_by_id)
  @page_type = mock_model(PageType)
  @page_type.stub!(:name)
  @page.stub!(:page_type).and_return(@page_type)
end

在这种情况下,我是在嘲笑页面&;PageType模型(对象)以及我调用的一些方法.

这使我能够运行这样的测试:

it "should be successful" do
  Page.should_receive(:find_by_id).and_return(@page)
  get 'show', :id => 1
  response.should be_success
end

我知道这个答案更具体,但我希望它能帮你一点忙.


Edit

好的,这是一个hello world的例子...

给出以下脚本(hello.rb):

class Hello
  def say
    "hello world"
  end
end

我们可以创建以下规范(hello_spec.rb):

require 'rubygems'
require 'spec'

require File.dirname(__FILE__) + '/hello.rb'

describe Hello do
  context "saying hello" do 
    before(:each) do
      @hello = mock(Hello)
      @hello.stub!(:say).and_return("hello world")
    end

    it "#say should return hello world" do
      @hello.should_receive(:say).and_return("hello world")
      answer = @hello.say
      answer.should match("hello world")
    end
  end
end

Ruby相关问答推荐

ruby 中嵌套哈希中相同键的平均值

如何修复 '535-5.7.8 用户名和密码未被接受.在 Devise 邮件确认错误中了解更多信息?

Ruby 中使用的-S标志是什么?

有没有办法在 Capybara 中保持登录状态?

如何增加 ruby​​ 应用程序的堆栈大小.递归应用程序获取:堆栈级别太深(SystemStackError)

Ruby on Rails 中是否有简写 if(没有 else)语句?

为什么在Ruby中用空格分隔的两个字符串连接在一起?

差异 - unless/if

RSpec:如何测试文件操作和文件内容

在 Pry 中有相当于 next 的吗?

Ruby 被空格分割

错误:Windows 的 SASS 安装

在 Ruby 脚本中解析命令行参数

Ruby 将 CSV 文件读取为 UTF-8 和/或将 ASCII-8Bit 编码转换为 UTF-8

Ruby 中的 to_s 与 to_str(以及 to_i/to_a/to_h 与 to_int/to_ary/to_hash)

class << self vs self.method with Ruby:什么更好?

Eclipse 的首选 Ruby 插件?

如何在遍历数组时使用 Array#delete?

Ruby:从 Ruby 中的变量创建哈希键和值

Ruby Activerecord IN 子句