機架不支持通過請求傳遞會話了(機架> = 1.0)。 Read this post for more detailed information on that.
在您的應用程序中設置會話變量的最佳方法是在您的應用程序中調用將設置會話變量的操作。舉例來說,如果你有你的應用程序內部的路由設置會話變量是這樣的:
post '/set_sess_var/:id'
session[:user_id] = params[:id]
end
讓我們假設有,你實際上想考這是使用另一種路由會話變量是這樣的:
get '/get_user_attributes'
User.find(session[:user_id]).attributes
end
然後在你的測試中,你應該首先調用設置會話的路由,然後進入使用它的另一條路由。這裏是RSpec的符號,因爲這是我用來測試:
it "should print out user attributes" do
user_id = 1
post '/set_sess_var/' + user_id
get '/get_user_attributes'
last_response.body.should == User.find(user_id).attributes
end
如果你要經常使用您的測試路線,然後你可以寫在你的測試文件來完成這個方法(如果您正在使用Rspec的,那麼這種方法就可以去參加你的spec_helper.rb或在您的controller_spec.rb文件):
def set_session_var(user_id)
post '/set_sess_var/' + user_id
end
然後調用它在測試中,當你需要它來進行設置:
it "should print out user attributes" do
set_session_var(1)
get '/get_user_attributes'
last_response.body.should == User.find(1).attributes
end
不是我想聽到的答案,但我想我沒有別的選擇,只能通過整個堆棧:(謝謝。 – Denny
是的,我聽到你的。有點討厭,但它不是很難,如果你做一個方法,你每次想要設置會話時都可以打電話,而且這樣做的目的是使機架更加安全(因此人們無法截獲會話並僞造未授權的會話),因此完成的目的是好的。 – Batkins
鏈接被打破。 –