rails unit / test get ActionView :: Template :: Error:undefined方法`name'代表nil:NilClass

时间:2013-01-08 17:09:11

标签: ruby-on-rails unit-testing

我的exercise_project中有一个简单的依赖项 patients belongs_to location
location has_many patients

我的patients_controller.rb文件

 class PatientsController < ApplicationController
    def location
       @location = Location.find(params[:id])
       place = @location.id
       @patients = Patient.where(:location_id => place)
    end

    def index
        @patients = Patient.paginate(:page => params[:page], :per_page => 20).order('id DESC')

        respond_to do |format|
        format.html
        format.json { render json: @patients }
    end
end

其他与使用rails默认生成的相同

我的patients#index文件

<table>
<% @patients.each do |patient| %>
   <tr>
    <td><%= patient.name %> </td>
    <td><%= patient.birthday %> </td>
    <td><%= patient.gender %></td>
    <td><%= medical_record(patient.id) %></td>
    <td><%= patient.status %></td>
    <td><%= link_to(patient.location.name, location_path(patient.location)) %> </td>
    <td><%= patient.viewed_count %></td>
   </tr>
     <td><%= link_to 'Show', patient_path(patient) %></td>
     <td><%= link_to 'Edit', edit_patient_path(patient) %></td>
     <td><%= link_to 'Destroy', patient_path(patient), :method => :delete, :confirm => 'Are YOU SURE?' %></td>
 <% end %>
</table>
    <%= link_to "create patient", new_patient_path %><hr>
    <%= link_to "Locations", locations_path %>

我为控制器写了一个单元/测试

require 'test_helper'

class PatientsControllerTest < ActionController::TestCase
  def setup
    @patient = patients(:one)
    @location = locations(:one)
    @patient.location_id = @location.id
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:patients)
  end

end

当我运行测试时,它返回
1) Error:
test_should_get_index(PatientsControllerTest):
ActionView::Template::Error: undefined method `name' for nil:NilClass

我知道它必须是控制器中的location方法,但我无法找到解决此问题的方法。
怎么能为这个控制器编写正确的测试?

---------------------更新------------------------- -----------
我把它改成了这个

require 'test_helper'

class PatientsControllerTest < ActionController::TestCase
  def setup
    @patient = patients(:one)
    @location = locations(:one)
    @patient.location_id = @location.id
  end

  test "should get index" do
    get :location
    get :index
    assert_response :success
    assert_not_nil assigns(:patients)
  end

end

并获取ActionController::RoutingError: No route matches {:controller=>"patients", :action=>"location"}

我的routes.rb

Patients::Application.routes.draw do
  resources :locations  
  resources :patients  

  root to: "locations#index"    
  match "patients/location/:id", :to => "patients#location", :as => :location_patients  
end

1 个答案:

答案 0 :(得分:1)

get :location

...(以及更多文本,因为stackoverflow需要30个字符的答案。)