使用 Rspec 进行多个 class 属性验证

multiple class attributes validation with Rspec

我有一个 class 有 3 个属性:game_finished、slots_selected 和 winner,我想同时检查三个

这样:如果 slots_selected 的值小于 9 且获胜者等于 0 并且 game_finished 为假,则测试应该通过。

如何使用 RSpec 验证该条件?

我试过这种方式:

it 'some description' do
    game = Game.new

    expect([game.game_finished, game.winner, game.slots_selected).to eq([false, 0, 8])
end

这里的问题是 slots_selected 是一个固定数字,我应该针对小于 9

的任何数字进行测试

我该怎么做?

最好对每个对象有单独的期望

expect(game.game_finished).to eq(false) 
expect(game.winner).to eq(0)
expect(game.slots_selected < 9).to be(true)

不过你好像把逻辑搞糊涂了。 TDD 应该可以帮助您编写更好的代码。将业务逻辑隔离为回答 true 或 false 类型问题所需的布尔值。但是您还没有明确说明您的逻辑规则应该是什么。这也许是一个更好的例子来说明你如何做到这一点:

let(:game) { Game.new }

it 'checks that game has not finished yet' do
   expect(game.finished?).to be false
end

it 'checks that game has not sarted yet' do
   expect(game.started?).to be false
end

it 'starts games less than 9 slots' do
  expect(game.slots_selected < 9).to be(true)
end

想法是您应该测试方法的输出或结果。先写规范,再让它们通过。