我正在尝试使用 Capybara 测试我的控制器。我尝试了很多方法,但由于某种原因,我无法让它看到 current_user 会话。当我运行我的规范时,我知道登录有效。在我的控制器测试之前,我也在访问登录页面。但是当 :logged_in 函数被击中时,它似乎总是将我重定向回来。
所以不确定我错过了什么?
这就是我所拥有的..
session_controller
def create
user = User.find_by_username(params[:username])
if( user && user.authenticate(params[:password]))
user.update_attribute(:token, User.token_digest)
flash[:notice] = "Success"
session[:user_id] = user.id
session[:token] = user.token
redirect_to dashboard_index_path
else
flash[:notice] = "Failed"
flash.now.alert = "Invalid user name or password"
render "new"
end
end
应用程序控制器
protect_from_forgery
before_filter :logged_in
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
def logged_in
if !current_user
redirect_to root_url
return
end
if session[:token] != current_user.token
redirect_to root_url
end
end
products_controller_spec
it 'Should display new product form' do
user_login
visit new_product_path
response.body.should have_content("<h1>Create New Product</h1>")
end
spec_helper.rb
def user_login
visit root_path #this is new_session
fill_in "username", :with => "admin"
fill_in "password", :with => "111111"
click_button "Login"
end