去除水豚特征测试的随机性

时间:2016-11-28 12:36:21

标签: rspec capybara stubbing

我正在使用Sinatra制作一个简单的摇滚,纸张,剪刀游戏,并使用rspec-capybara进行测试。游戏对抗随机化摇滚,纸张或剪刀的计算机对手。我正在为网页结果编写测试。我正在扼杀对手的反应,总是选择纸张让球员输球(因为他选择摇滚)

scenario "Player chooses rock, and the computer chooses paper." do
single_player_sign_in_and_play
click_button('rock')
allow(game).to receive_message_chain(:player2, :weapon) {:paper}
allow(game).to receive(:outcome).and_return("You lose!")
allow(game).to receive(:message).and_return("Your opponent chose #{game.player2.weapon}. #{game.outcome}")
expect(page).to have_content("Your opponent chose paper. You lose!")

我希望对手永远拥有:纸张作为武器,所以玩家输了:页面应该有内容:“你的对手选择了纸张。你输了!”

2 个答案:

答案 0 :(得分:0)

在调用click_button('rock')

之前,您应该存根调用
scenario "Player chooses rock, and the computer chooses paper." do
  allow(game).to receive_message_chain(:player2, :weapon) {:paper}
  allow(game).to receive(:outcome).and_return("You lose!")
  allow(game).to receive(:message).and_return("Your opponent chose paper. You lose!")
  single_player_sign_in_and_play
  click_button('rock')
  expect(page).to have_content(game.message)
end

我建议不要在期望中使用game.message,而是使用Your opponent chose paper. You lose!。您还可以考虑将存根移动到before

答案 1 :(得分:0)

双打不能传递给Capybara功能测试。双打只应用于单元测试!以下代码通过。

scenario "Player chooses rock, and the computer chooses paper." do
allow_any_instance_of(Opponent).to receive(:weapon).and_return(:paper)
single_player_sign_in_and_play
click_button('rock')
save_and_open_page
expect(page).to have_content("Your opponent chose paper. You lose!")