0

我的练习项目中有一个简单的依赖项
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
4

1 回答 1

1
get :location

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

于 2013-01-08T17:17:03.113 回答