NoMethodError:nil的未定义方法'clients':NilClass

时间:2016-04-28 21:24:14

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

我遇到臭名昭着的NoMethodError,即使在浏览了SO帖子的数量之后,我似乎也无法破解。

注意:我在Cloud9开发环境中运行

我正在建立一个生产力网站,用户可以在其中拥有自己的客户,项目等。

我正在尝试运行 clients_display_test.rb 测试,并收到以下终端错误。

任何帮助都会受到赞赏,但我会问,如果你确定我的错误在哪里,请说明我缺乏技术理解的地方:)

  1) Error:
ClientsDisplayTestTest#test_profile_display:
NoMethodError: undefined method `clients' for nil:NilClass
    app/controllers/clients_controller.rb:4:in `index'
    test/integration/clients_display_test_test.rb:11:in `block in <class:ClientsDisplayTestTest>'

48 runs, 127 assertions, 0 failures, 1 errors, 0 skips

clients_display_test.rb

require 'test_helper'

class ClientsDisplayTestTest < ActionDispatch::IntegrationTest
  include ApplicationHelper

  def setup
    @user = users(:Robert)
  end 

  test "profile display" do
    get '/clients'
    assert_template "clients/index"
    assert_select 'title', "Clients"
  end
end

附上一些.rb文件,希望可以提供帮助:

clients_controller.rb

class ClientsController < ApplicationController

    def index
        @clients = current_user.clients.paginate(page: params[:page])
    end

    def show
    end
end

routes.rb

Rails.application.routes.draw do

  get 'password_resets/newedit'

  root              'static_pages#home'
  get 'about' =>    'static_pages#about'
  get 'signup' =>   'users#new'

  get 'login' =>    'sessions#new'
  #the page for new session
  post 'login' =>   'sessions#create'
  #creates a new session
  delete 'logout' =>'sessions#destroy'
  #deletes the session
  get '/clients' => 'clients#index'
  get '/clients/show' => 'clients#show'

  resources :users
  resources :clients 
  resources :account_activations, only: [:edit]
  resources :password_resets,     only: [:new, :create, :edit, :update]
end

客户观看次数

index.html.erb

    <%= provide(:title, 'Clients') %>

<div class="clients-container container"> 
    <div class="row">
        <!-- Add pagination later for multiple folders over multiple pages --> 
    <% if current_user.clients.any? %>
        <%= render @clients %> 
        <%= will_paginate @clients %>
    <% end %>
    </div>
</div>

_client.html.erb

<div class="col-md-2 client-folder" style="margin: 10px" id="client - <%= client.id %>">
  <span class="clientName" ><%= client.client_name %></span> <br>
  <span class="contactName"><%= client.contact_name %></span>
</div>

1 个答案:

答案 0 :(得分:1)

看来你的current_user是零。您必须在访问页面之前在测试中登录您的用户,否则current_user方法将返回nil。

如果您正在使用Devise进行身份验证,那么可以使用测试帮助程序,更多相关信息:

https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-3-and-4-(and-RSpec)