ruby-on-rails - RSpec 如何测试传递给方法的参数数据类型

标签 ruby-on-rails ruby rspec tdd bdd

我需要测试传递的参数类型是一个整数。这是我的测试规范:

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

最佳答案

你可以添加一个 block 到receive来检查方法参数:

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

您可以在 Arbitrary Handling section 中找到详细信息rspec-mocks 文档。

更新:您也可以使用与 should 语法相同的方法:

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

关于ruby-on-rails - RSpec 如何测试传递给方法的参数数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43555005/

相关文章:

css - Ruby on Rails 图像显示

html - Bootstrap 3 的事件按钮

ruby-on-rails - ArgumentError(需要帐户 SID 和身份验证 token ):

ruby-on-rails - 测试 has_one 关系?

ruby-on-rails - Ruby on Rails,如何在登录页面上停止导航栏呈现?

ruby-on-rails - Rails - 如何从模型创建数据库表(我没有迁移脚本)

javascript - Rails 从远程获取事件触发器 :true

ruby-on-rails - Selenium 测试在 Ubuntu 和 Mac OSX 上的表现不同是否有原因?

ruby-on-rails - 工厂女孩 : NameError unintialized constant for one of the factories

ruby-on-rails - 让 Rails URL 助手自动输出 https url