age*_*217 37 ruby unit-testing rspec rspec-mocks
我是模拟对象的新手,我正在尝试学习如何在RSpec中使用它们.有人可以发布一个示例(一个hello RSpec Mock对象世界类型示例),或者关于如何使用RSpec模拟对象API的链接(或任何其他参考)?
Bri*_*ian 64
这是我在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
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我正在嘲笑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
Run Code Online (Sandbox Code Playgroud)
我知道这个答案更具特定的轨道,但我希望它能帮到你一点点.
编辑
好的,所以这是一个你好世界的例子......
给出以下脚本(hello.rb):
class Hello
def say
"hello world"
end
end
Run Code Online (Sandbox Code Playgroud)
我们可以创建以下规范(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
Run Code Online (Sandbox Code Playgroud)
mock基于此github pull弃用.
现在我们可以使用double- 更多在这里......
before(:each) do
@page = double("Page")
end
it "page should return hello world" do
allow(@page).to receive(:say).and_return("hello world")
answer = @page.say
expect(answer).to eq("hello world")
end
Run Code Online (Sandbox Code Playgroud)
我没有足够的分数来回答评论,但我想说接受的答案也帮助我试图找出如何以随机值存根.
我需要能够存储一个随机分配的对象的实例值,例如:
class ClumsyPlayer < Player do
def initialize(name, health = 100)
super(name, health)
@health_boost = rand(1..10)
end
end
Run Code Online (Sandbox Code Playgroud)
然后在我的规范中,我有一个问题,就是要弄清楚如何将笨拙的玩家的随机健康状况存根,以测试当他们得到治疗时,他们会得到适当的健康促进.
诀窍是:
@player.stub!(health_boost: 5)
Run Code Online (Sandbox Code Playgroud)
所以这stub!是关键,我一直在使用,stub并且仍然得到随机的rspec传递和失败.
谢谢Brian
| 归档时间: |
|
| 查看次数: |
42880 次 |
| 最近记录: |