RSpec返回'未定义的局部变量或方法`signin_path''

时间:2013-10-09 20:23:22

标签: ruby-on-rails ruby rspec

当我运行RSpec时,我得到4个错误:

undefined local variable or method `signin_path' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x4203fa8>

但我正在运行其他使用此帮助程序和路径的测试没有问题,只有在关系控制器测试中才能使用它。

relationship_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

Utilities.rb:

def sign_in(user)
    visit signin_path
    fill_in 'Email',        with: user.email.upcase
    fill_in 'Password', with: user.password
    click_button 'Sign In'
    cookies[:remember_token] = user.remember_token
end

routes.rb中:

  resources :users do
    member do
      get :following, :followers
    end
  end

  resources :sessions,      only: [:create, :destroy, :new]
  resources :microposts,    only: [:create, :destroy]
  resources :relationships, only: [:create, :destroy]

  # Application Root
  root to: 'static_pages#home'

  # Static Pages
  match '/help', to: 'static_pages#help'
  match '/about', to: 'static_pages#about'
  match '/contact', to: 'static_pages#contact'

  # Users
  match '/signup',  to: 'users#new'
  match '/signin',  to: 'sessions#new'
  match '/signout', to: 'sessions#destroy', via: :delete

1 个答案:

答案 0 :(得分:1)

控制器规范无法以与功能规范相同的方式与页面交互,因此您的sign_in实用程序将不适用于它们。

如果您的控制器规格依赖于已登录的用户,则需要存根current_user方法。如果你使用Devise,这里是他们wiki的有用页面:https://github.com/plataformatec/devise/wiki/How-To:-Stub-authentication-in-controller-specs