本文介绍了发出请求之前规范中的 Rspec 2.7 访问控制器会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Rspec 测试我的控制器,但在向路径发出请求之前,我似乎无法设置当前被测控制器的会话变量.例如这有效:
I'm testing my controllers using Rspec and I can't seem to set the session variable of the current controller under test before making the request to the path.For example this works:
describe "GET /controller/path" do
it "if not matching CRSF should display message" do
get controller_path
request.session[:state] = "12334"
end
end
这不起作用(我收到一条错误消息,说 session 不是 Nil 类的方法):
This doesn't work (i get an error saying session is not a method of Nil class):
describe "GET /controller/path" do
it "if not matching CRSF should display message" do
request.session[:state] = "12334"
get controller_path
end
end
有什么想法吗?
推荐答案
RSpec 的新版本做得很好,看:
With new version of RSpec this is done pretty nice, look:
describe SessionController do
# routes are mapped as:
# match 'login' => 'session#create'
# get 'logout' => 'session#destroy'
describe "#create" do
context "with valid credentials" do
let :credentials do
{ :email => '[email protected]', :password => 'secret' }
end
let :user do
FactoryGirl.create(:user, credentials)
end
before :each do
post '/login', credentials
end
it "creates a user session" do
session[:user_id].should == user.id
end
end
# ...
end
describe "#destroy" do
context "when user logged in" do
before :each do
get "/logout", {}, { :user_id => 123 } # the first hash is params, second is session
end
it "destroys user session" do
session[:user_id].should be_nil
end
# ...
end
end
end
你也可以在 before(:each)
块中简单地使用 request.session[:user_id] = 123
,但上面看起来更漂亮.
You can also use simply request.session[:user_id] = 123
inside before(:each)
block, but above looks pretty nicer.
这篇关于发出请求之前规范中的 Rspec 2.7 访问控制器会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!