私の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
他はレールのデフォルトで生成するものと同じです
私の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