![](/img/trans.png)
[英]how to test a method call once with one argument and one block in rspec
[英]RSpec how to test an argument data type passed to a method
我需要测试传递的参数类型是整数。 这是我的测试规格:
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
提前致谢
更新:
抱歉使用旧的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
您可以添加一个模块来receive
检查方法PARAMS:
expect(ball_spin).to receive(:create_ball_spin) do |arg|
expect(arg.size).to be_a Integer
end
您可以在rspec-mocks
文档的“ Arbitrary Handling
部分中找到详细信息。
更新:此外,您可能会使用should
语法的相同方法:
ball_spin.should_receive(:create_ball_spin) do |arg|
arg.should be_a Integer
end
我认为原因是5是Fixnum的实例,而不是Integer:
2.2.1 :005 > 5.instance_of?(Fixnum)
=> true
2.2.1 :006 > 5.instance_of?(Integer)
=> false
更新:好的,我已经尝试了您的代码,问题是Integer而不是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
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
请参阅“ 参数匹配器”部分。
顺便说一句,您使用旧的RSpec语法,并且可能要考虑将测试套件更新为新的expect
语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.