我正在写一个保龄球得分计算器,我正在尝试设置RSpec测试,但由于某种原因我无法让我的测试正常工作。
players_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
players_controller.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
有问题的规格是players_controller_spec.rb,在测试开始时我正在创建一个有4个玩家和每个玩家10帧的新游戏。在每次测试之前,我将某个帧的值设置为我想要测试的值。上面的测试是一个例子,我想确保在最后一帧的第三个碗上保持5分,正确地更新分数。但是,即使在调试器中我看到分数在框架中更新(当我在控制器方法中调试时),一旦我返回到Rspec测试,它就不起作用。它预计25但是没有。关于如何在规范和控制器之间传输实例变量,我有什么遗漏吗?
答案 0 :(得分:0)
首先,没有'转移'。控制器和示例是2个完全独立的对象,每个对象都有自己的实例变量(您可以使用assigns
规范帮助程序来检索控制器实例变量的值)。
这不是您问题的根本原因。即使在控制器执行之前,您也有一个@game
实例变量,这是您感兴趣的游戏。但是对于activerecord,每次执行Game.find
时,您都会收到单独的ruby对象(对应于相同的数据库行)。从数据库加载行后,它不会注意到对其后面的数据库所做的更改。
您可以使用@game.reload
作为旁注,如果将大部分逻辑推入您的某个模型而不是坐在控制器中,这种东西更容易使用。