首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Rails自定义在控制器测试中不注册sign_in用户

Rails自定义在控制器测试中不注册sign_in用户
EN

Stack Overflow用户
提问于 2014-08-28 21:26:18
回答 1查看 30关注 0票数 1

我创建了基于Hartl的Rails教程的身份验证系统,并且在控制器测试方面遇到了问题。

engagements_controller_spec.rb

代码语言:javascript
运行
复制
require 'spec_helper'

describe EngagementsController do
  describe "GET show" do
    let(:user) { FactoryGirl.create(:user) }
    before { sign_in user }

    it "assigns requested engagement to @engagement" do
      engagement = FactoryGirl.create(:engagement, user: user)
      get :show, id: engagement
      assigns[:engagement].should eq(engagement)
    end

    it "renders :show" do
      engagement = FactoryGirl.create(:engagement, user: user)
      get :show, :id => engagement.id
      expect(response).to render_template("show")
    end
  end
end

我得到的错误:

代码语言:javascript
运行
复制
 EngagementsController GET show renders :show
 Failure/Error: expect(response).to render_template("show")
   expecting <"show"> but rendering with <[]>
 # ./spec/controllers/engagements_controller_spec.rb:37:in `block (3 levels) in < top (required)>'

 EngagementsController GET show assigns requested engagement to @engagement
 Failure/Error: assigns[:engagement].should eq(engagement)  
 expected: #<Engagement id: 42, title: "Coding", content: "Got in the zone with coding", user_id: 46, created_at: "2014-08-28 21:08:43", updated_at: "2014-08-28 21:08:43", photo_file_name: nil, photo_content_type: nil, photo_file_size: nil, photo_updated_at: nil>
        got: nil
   (compared using ==)
 # ./spec/controllers/engagements_controller_spec.rb:31:in `block (3 levels) in < top (required)>'

engagements_controller.rb

代码语言:javascript
运行
复制
class EngagementsController < ApplicationController
  before_action :signed_in_user
  before_action :correct_user, only: [:show]

  def show
    @engagement = Engagement.find(params[:id])
  end

  private

  def correct_user
    @engagement = current_user.engagements.find_by_id(params[:id])
    if @engagement.nil? && !current_user.try(:admin)
      redirect_to root_url
    end
  end

我已经试过了我所能找到的所有答案,而没有运气。任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-29 15:07:38

我想出了答案。以前在控制器里我有:

代码语言:javascript
运行
复制
before { sign_in user }

然而,在控制器规范中,Capybara应该被禁用。因此,使用:

代码语言:javascript
运行
复制
before { sign_in user, no_capybara: true }

让它发挥作用。

我明白为什么这样做,但不足以解释它。如果有人有很好的解释,那就太好了!:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25558289

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档