在编写请求规范时,如何设置会话和/或存根控制器方法?我正在尝试在我的集成测试中对身份验证进行存根 - rspec / requests
这是一个测试的示例
require File.dirname(__FILE__) + '/../spec_helper'
require File.dirname(__FILE__) + '/authentication_helpers'
describe "Messages" do
include AuthenticationHelpers
describe "GET admin/messages" do
before(:each) do
@current_user = Factory :super_admin
login(@current_user)
end
it "displays received messages" do
sender = Factory :jonas
direct_message = Message.new(:sender_id => sender.id, :subject => "Message system.", :content => "content", :receiver_ids => [@current_user.id])
direct_message.save
get admin_messages_path
response.body.should include(direct_message.subject)
end
end
end
这个帮助程序:
module AuthenticationHelpers
def login(user)
session[:user_id] = user.id # session is nil
#controller.stub!(:current_user).and_return(user) # controller is nil
end
end
处理身份验证的ApplicationController:
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :current_user
helper_method :logged_in?
protected
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def logged_in?
!current_user.nil?
end
end
为什么无法访问这些资源?
1) Messages GET admin/messages displays received messages
Failure/Error: login(@current_user)
NoMethodError:
undefined method `session' for nil:NilClass
# ./spec/requests/authentication_helpers.rb:3:in `login'
# ./spec/requests/message_spec.rb:15:in `block (3 levels) in <top (required)>'
ActionDispatch::IntegrationTest
的设计目的是模拟一个或多个用户通过浏览器进行交互,而无需使用真实的浏览器。在单个示例中可能会有多个用户(即会话)和多个控制器,并且会话/控制器对象是在最后一个请求中使用的。在请求之前,您无法访问它们。 - David Chelimskypage.driver.post
和Capybara一起使用。 - Ian Yangpage.driver.post
可能是一种反模式。 - Epigene