测试不通过:未定义的方法`authenticate!'为零:NilClass?

时间:2012-10-31 22:51:18

标签: ruby-on-rails rspec

我有以下失败:

Failures:

  1) RelationshipsController creating a relationship with Ajax should increment the Relationship count
     Failure/Error: xhr :post, :create, relationship: { followed_id: other_user.id }
     NoMethodError:
       undefined method `authenticate!' for nil:NilClass
     # ./spec/controllers/relationships_controller_spec.rb:14:in `block (4 levels) in <top (required)>'
     # ./spec/controllers/relationships_controller_spec.rb:13:in `block (3 levels) in <top (required)>'

但是很奇怪,如果我访问该网站,事情就有效(如果我点击关注按钮,followers计数器会增加:

enter image description here

最奇怪的是,没有任何身份验证! relationships_controller_spec.rb

中的方法
require 'spec_helper'

describe RelationshipsController do

  let(:user) { FactoryGirl.create(:user) }
  let(:other_user) { FactoryGirl.create(:user) }

  before { sign_in user }

  describe "creating a relationship with Ajax" do

    it "should increment the Relationship count" do
      expect do
        xhr :post, :create, relationship: { followed_id: other_user.id }
      end.to change(Relationship, :count).by(1)
    end

    it "should respond with success" do
      xhr :post, :create, relationship: { followed_id: other_user.id }
      response.should be_success
    end
  end

  describe "destroying a relationship with Ajax" do

    before { user.follow!(other_user) }
    let(:relationship) { user.relationships.find_by_followed_id(other_user) }

    it "should decrement the Relationship count" do
      expect do
        xhr :delete, :destroy, id: relationship.id
      end.to change(Relationship, :count).by(-1)
    end

    it "should respond with success" do
      xhr :delete, :destroy, id: relationship.id
      response.should be_success
    end
  end
end

在控制器中都没有:

class RelationshipsController < ApplicationController
  before_filter :authenticate_user!

  def create
    @user = User.find(params[:relationship][:followed_id])
    current_user.follow!(@user)
    respond_to do |format|
      format.html { redirect_to @user }
      format.js
    end
  end

  def destroy
    @user = Relationship.find(params[:id]).followed
    current_user.unfollow!(@user)
    respond_to do |format|
      format.html { redirect_to @user }
      format.js
    end
  end
end

可能是什么问题?

(顺便说一句,这些测试是在Ruby on Rails Tutorial之后进行的。之后,我删除了所有身份验证系统,因为我想使用设计。)

2 个答案:

答案 0 :(得分:22)

设置config.include Devise::TestHelpers, :type => :controller不再适用于更高版本的Devise。您需要做的是注销匿名用户以设置适当的变量:

before :each do
  sign_out :user
end

答案 1 :(得分:15)

我不得不补充一下:

<强> spec_helpers.rb:

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end