我正在编写一个保龄球分数计算器,并且我正在尝试设置 RSpec 测试,但由于某种原因,我无法让我的测试正常工作。
player_controller_spec.rb:
require 'spec_helper'
describe PlayersController do
let(:player_names) { ["player1",
"player2",
"player3",
"player4"] }
describe "POST bowl" do
before(:each) do
@game = Game.create!
player_names.each do |name|
Player.create!(:name => name)
end
@game.players = Player.all
Player.all.each do |player|
(0..9).each do |number|
player.frames << Frame.create(:number => number)
end
end
end
describe "for the player's third bowl" do
before(:each) do
@game.players[@game.current_player].frames[9].update_attributes({:number => 9, :first_bowl => "X", :second_bowl => "X", :score => 20})
@game.update_attributes({:current_player => 0, :current_frame => 9})
end
describe "if the bowl is a number score" do
before(:each) do
post :bowl, {:score => "5", :id => @game.id}
end
it "should update the player's score" do
@game.players[@game.current_player].frames[@game.current_frame].score.should == 25
end
end
end
end
end
玩家控制器.rb
def bowl
@game = Game.find(params[:id])
@score = params[:score]
@current_player = @game.current_player
@current_frame = @game.current_frame
@player = @game.players[@current_player]
@frame = @player.frames[@current_frame]
if @frame.first_bowl.nil?
@frame.first_bowl = @score
if @score == "/"
raise "Error"
end
if @score == "X" && @frame.number == 9
@frame.bonus = 2
end
@frame.score = (/\A[0-9]\z/ === @score ? @score.to_i : 10)
elsif @frame.second_bowl.nil?
@frame.second_bowl = @score
if @frame.score + @score.to_i > 10
raise "Error"
end
if @score == "X"
if @frame.number != 9 || (@frame.number == 9 && @frame.first_bowl != "X") # can't be a spare has to be number or strike
raise "Error"
end
end
if @score == "/" && @frame.number == 9
@frame.bonus = 1
end
if /\A[0-9]\z/ === @score
@frame.score += @score.to_i
elsif @score == "/"
@frame.score = 10
elsif @score == "X"
@frame.score = 20
end
elsif @frame.third_bowl.nil?
@frame.third_bowl = @score
if @frame.number != 9
raise "Error"
end
@frame.bonus = nil
@frame.update_attributes({:score => (/\A[0-9]\z/ === @score ? @frame.score + @score.to_i : @frame.score + 10)})
else
raise "Error"
end
@frame.save
if @game.current_frame > 0
@prev_frame = @player.frames[@frame.number-1]
if @prev_frame.nil?
@prev_frame = Frame.create(:number => @game.current_frame-1)
@player.frames << @prev_frame
@player.frames = @player.frames.sort_by { |f| f.number }
end
update_scores
end
有问题的规范是 player_controller_spec.rb,在测试开始时,我正在创建一个有 4 个玩家的新游戏,每个玩家有 10 帧。在每次测试之前,我都会设置某个帧的值以适合我要测试的内容。上面的测试是一个示例,我想确保在最后一帧的第三个保龄球上保龄球得分为 5 正确更新了得分。但是,即使在调试器中我看到分数在框架中更新(当我在控制器方法中调试时),一旦我返回 Rspec 测试,它就不起作用。它预计为 25,但结果为零。关于如何在规范和控制器之间传输实例变量,我有什么遗漏吗?