我是模拟对象的新手,我正在尝试学习如何在 RSpec 中使用它们。有人可以发布有关如何使用 RSpec 模拟对象 API 的示例(hello RSpec Mock 对象世界类型示例)或链接(或任何其他引用)吗?
最佳答案
这是我为 Rails 应用程序中的 Controller 测试所做的简单模拟示例:
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
在本例中,我模拟了 Page 和 PageType 模型(对象)并删除了我调用的一些方法。
这使我能够运行这样的测试:
it "should be successful" do
Page.should_receive(:find_by_id).and_return(@page)
get 'show', :id => 1
response.should be_success
end
我知道这个答案更具体,但我希望它能对您有所帮助。
编辑
好的,这是一个 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 - RSpec 模拟对象示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3622604/