Kri*_* MP 2 ruby tdd bdd rspec ruby-on-rails
我需要测试传递的参数类型是整数。这是我的测试规范:
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
Run Code Online (Sandbox Code Playgroud)
我的代码:
class BallSpin
def create_ball_spin n
"Created a ball spin #{n} times" if n.is_a? Integer
end
end
Run Code Online (Sandbox Code Playgroud)
提前致谢
更新:
为使用旧的 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
Run Code Online (Sandbox Code Playgroud)
您可以添加一个块receive来检查方法参数:
expect(ball_spin).to receive(:create_ball_spin) do |arg|
expect(arg.size).to be_a Integer
end
Run Code Online (Sandbox Code Playgroud)
您可能会发现在细节Arbitrary Handling部分的rspec-mocks文档。
更新:您也可以在should语法上使用相同的方法:
ball_spin.should_receive(:create_ball_spin) do |arg|
arg.should be_a Integer
end
Run Code Online (Sandbox Code Playgroud)