如何通过rspec测试控制器中更新的会话变量

时间:2013-08-10 00:11:18

标签: ruby-on-rails rspec controller

我正在尝试使用rspec编写测试,测试会话变量是否已正确更改:

这是我要测试的GamesController的一部分:

def change_player
  if session[:player] == 0
    session[:player] = 1
  else
    session[:player] = 0
  end    
end

这是我的game_spec.rb文件:

require "spec_helper"

describe GamesController do
 describe "#change_player" do
   it "should change player to 1" do
     session[:player] = 0

     get :change_player

     assigns(session[:player]).should == 1
   end
 end
end

这是我运行测试时收到的错误消息:

Failures:

  1) GamesController#change_player should set player to 0
     Failure/Error: session[:player] = 0
     NameError:
       undefined local variable or method `session' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x00000103b3b0d8>
     # ./spec/features/game_spec.rb:6:in `block (3 levels) in <top (required)>'

Finished in 0.01709 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/features/game_spec.rb:5 # GamesController#change_player should set player to 0

由于

1 个答案:

答案 0 :(得分:4)

问题是rspec不知道这是一个控制器测试(不在spec/controllers文件夹中)

您需要指定

describe GamesController, :type => :controller do
    ...
end