【问题标题】:controller is Nil in rspec test控制器在 rspec 测试中为 Nil
【发布时间】:2015-05-20 16:00:56
【问题描述】:

我有以下 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?

这是因为controllernil。这里有什么问题导致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 平台信息: 红宝石:2.0.0p643 导轨:4.2.1 RSpec:3.2.2

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    这是一个请求规范(基本上是一个 Rails 集成测试),旨在跨越多个请求,可能跨控制器。

    controller 变量由集成测试提供的请求方法设置(getputpost 等)

    如果您改为使用 capybara DSL(访问、点击等),则永远不会调用集成测试方法,因此 controller 将为零。使用 capybara 时,您无法访问单个控制器实例,因此您无法测试 signed_in? 返回的内容 - 您必须测试更高级别的行为(例如页面上的内容)。

    【讨论】:

    • 我将此测试用例移至控制器测试用例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多