我是模拟对象的新手,我正在尝试学习如何在 RSpec 中使用它们。有人可以发布一个关于如何使用 RSpec 模拟对象 API 的示例(hello RSpec Mock 对象世界类型示例)或链接(或任何其他参考)吗?
以下是我在 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
在本例中,我模拟了 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
我知道这个答案更具体,但我希望它对您有所帮助。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)