2017-04-22 76 views
1

我需要测试传入的参数类型是一个整数。这里是我的测试规范:RSpec如何测试传递给方法的参数数据类型

require 'ball_spin' 

RSpec.describe BallSpin do 
    describe '#create_ball_spin' do 
    subject(:ball_spin) { BallSpin.new } 
    it 'should accept an integer argument' do 
     expect(ball_spin).to receive(:create_ball_spin).with(an_instance_of(Integer)) 
     ball_spin.create_ball_spin(5) 
    end 
    end 
end 

我的代码:

class BallSpin 
    def create_ball_spin n 
    "Created a ball spin #{n} times" if n.is_a? Integer 
    end 
end 

在此先感谢

UPDATE:

道歉使用旧RSpec的语法,下面我更新了我的代码使用最新的:

it 'should accept an integer argument' do 
    expect(ball_spin).to receive(:create_ball_spin).with(an_instance_of(Integer)) 
    ball_spin.create_ball_spin(5) 
end 

回答

1

您可以将块添加到receive检查方法PARAMS:

expect(ball_spin).to receive(:create_ball_spin) do |arg| 
    expect(arg.size).to be_a Integer 
end 

您可能会发现rspec-mocks文档Arbitrary Handling section细节。

UPDATE:您也可以使用同样的方法与should语法:

ball_spin.should_receive(:create_ball_spin) do |arg| 
    arg.should be_a Integer 
end 
+0

谢谢回答,我得到了一个错误NoMethodError你好:未定义的方法'收到”为#

+1

@Kris MP,您使用的是什么版本Rspec的呢? –

0

receive匹配的使用情况是符合规范的是一个方法被人称为。但值得注意的是,匹配器本身不会调用该方法,也不会测试该方法是否存在,或者可能参数的列表是否与给定模式匹配。

好像你的代码不调用该方法在所有。应通过的简单测试可能如下所示:

subject(:ball_spin) { BallSpin.new } 

it 'is called with an integer argument' do 
    ball_spin.should_receive(:create_ball_spin).with(an_instance_of(Integer)) 
    ball_spin.create_ball_spin(5) # method called 
end 

it 'is not called' do 
    ball_spin.should_not_receive(:create_ball_spin) 
    # method not called 
end 

请参阅部分Argument Matcher

顺便说一句,你使用旧的RSpec的语法和可能要考虑更新您的测试套件的新expect语法。

+0

已经试过这个,但仍然没有运气 –

+0

@KrisMP我更新了我的答案。因为我觉得你觉得匹配器的工作方式不符合设计要求。 – spickermann

+0

我已更新我的问题并调整为RSpec新语法 –

1

我想原因是,5 Fixnum对象,而不是整数的一个实例:

2.2.1 :005 > 5.instance_of?(Fixnum) 
    => true 
2.2.1 :006 > 5.instance_of?(Integer) 
    => false 

UPDATE: 好吧,我想你的代码和问题是整数,而不是Fixnum对象。这是正确的断言:

RSpec.describe BallSpin do 
    describe '#create_ball_spin' do 
    subject(:ball_spin) { BallSpin.new } 
    it 'should accept an integer argument' do 
     expect(ball_spin).to receive(:create_ball_spin).with(an_instance_of(Fixnum)) 
     ball_spin.create_ball_spin(5) 
    end 
    end 
end 
相关问题