控制器在 rspec 测试中为 Nil
controller is Nil in rspec test
我有以下 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 是:
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
这是一个请求规范(基本上是一个 rails 集成测试),旨在跨越多个请求,可能跨控制器。
controller
变量由集成测试提供的请求方法设置(get
、put
、post
等)
如果您改为使用水豚 DSL(访问、点击等),则永远不会调用集成测试方法,因此 controller
将为零。使用水豚时,您无权访问单个控制器实例,因此您无法测试 signed_in?
returns 之类的东西 - 您必须测试更高级别的行为(例如页面上的内容) .
我有以下 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 是:
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
这是一个请求规范(基本上是一个 rails 集成测试),旨在跨越多个请求,可能跨控制器。
controller
变量由集成测试提供的请求方法设置(get
、put
、post
等)
如果您改为使用水豚 DSL(访问、点击等),则永远不会调用集成测试方法,因此 controller
将为零。使用水豚时,您无权访问单个控制器实例,因此您无法测试 signed_in?
returns 之类的东西 - 您必须测试更高级别的行为(例如页面上的内容) .