RSpec 模拟对象示例 [英] RSpec Mock Object Example
问题描述
我是模拟对象的新手,我正在尝试学习如何在 RSpec 中使用它们.有人可以发布一个示例(你好 RSpec Mock 对象世界类型示例),或关于如何使用 RSpec 模拟对象 API 的链接(或任何其他参考)?
I am new to mock objects, and I am trying to learn how to use them in RSpec. Can someone please post an example (a hello RSpec Mock object world type example), or a link (or any other reference) on how to use the RSpec mock object API?
推荐答案
以下是我为 Rails 应用程序中的控制器测试所做的简单模拟示例:
Here's an example of a simple mock I did for a controller test in a rails application:
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 模型(对象)以及我调用的一些方法.
In this case, I'm mocking the Page & PageType models (Objects) as well as stubbing out a few of the methods I call.
这使我能够运行这样的测试:
This gives me the ability to run a tests like this:
it "should be successful" do
Page.should_receive(:find_by_id).and_return(@page)
get 'show', :id => 1
response.should be_success
end
我知道这个答案更具体,但我希望它对您有所帮助.
I know this answer is more rails specific, but I hope it helps you out a little.
编辑
好的,这里有一个 hello world 示例...
Ok, so here is a hello world example...
给定以下脚本(hello.rb):
Given the following script (hello.rb):
class Hello
def say
"hello world"
end
end
我们可以创建以下规范(hello_spec.rb):
We can create the following spec (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
这篇关于RSpec 模拟对象示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!