我遵循RSpec测试:
require 'rails_helper'
require 'spec_helper'
RSpec.describe "Users", type: :request do
describe "sign in/out" do
describe "success" do
it "should sign a user in and out" do
attr = {:name=>"Test1",
:email => "dmishra@test.org",
:password => "foobar",
:password_confirmation => "foobar"
}
user = User.create(attr)
visit signin_path
fill_in "Email", :with => user.email
fill_in "Password", :with => user.password
puts page.body
click_button "Sign in"
controller.should be_signed_in
click_link "Sign out"
controller.should_not be_signed_in
end
end
end
end
我收到以下错误:
Failure/Error: controller.should be_signed_in
expected to respond to `signed_in?
这是因为controller
是nil
。这里有什么问题导致controller
成为nil
?
控制器类是:
class SessionsController < ApplicationController
def new
@title = "Sign in"
end
def create
user = User.authenticate(params[:session][:email],
params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid email/password combination."
@title = "Sign in"
render 'new'
else
sign_in user
redirect_to user
end
end
def destroy
sign_out
redirect_to root_path
end
end
signed_in
方法在会话助手中定义,包括在内。
Ruby平台信息: Ruby:2.0.0p643 Rails:4.2.1 RSpec:3.2.2
答案 0 :(得分:4)
这是一个请求规范(基本上是一个rails集成测试),旨在跨越多个请求,可能跨越控制器。
controller
变量由集成测试提供的请求方法设置(get
,put
,post
等。)
如果您使用capybara DSL(访问,点击等),那么集成测试方法永远不会被调用,因此controller
将为零。使用capybara时,您无法访问单个控制器实例,因此您无法测试诸如signed_in?
返回的内容 - 您必须测试更高级别的行为(例如页面上的内容)。