【问题标题】:RSpec ActiveRecord::RecordNotFoundRSpec ActiveRecord::RecordNotFound
【发布时间】:2015-12-04 04:53:46
【问题描述】:

我很难通过考试:

错误:

Failure/Error: post :create, { appointment: { dentist_id: '1', patient_id: '2', appt_date: '2015-12-05 09:00:00' } }
 ActiveRecord::RecordNotFound:
   Couldn't find Dentist with 'id'=

约会控制器:

def create
 @dentist = Dentist.find(params[:dentist_id])
 @appointment = @dentist.appointments.new(appointment)
  if Appointment.exists?(:appt_date => @appointment.appt_date)
   render :new
  else
   @appointment.save
   redirect_to dentist_path(@dentist)
  end
end

预约说明:

describe 'POST #create' do
 it 'assigns a newly created appointment as @appointment' do
  post :create, { appointment: { dentist_id: '1', patient_id: '2', appt_date: '2015-12-05 09:00:00' } }
  expect(assigns(:appointment)).to be_a(Appointment)
  expect(assigns(:appointment)).to be_persisted
 end
end

我错过了什么?非常感激任何的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rspec


    【解决方案1】:

    在您的请求中,您正在执行post :create, { appointment: { dentist_id: '1', ... } },这意味着您的控制器中的params[:dentist_id] 将是nil(请注意您如何在请求参数中的appointment 下嵌套dentist_id)。要解决此问题,请将控制器操作中的 @dentist = Dentist.find(params[:dentist_id]) 更改为 @dentist = Dentist.find(params[:appointment][:dentist_id]),或将您的请求更改为 post :create, { dentist_id: '1', appointment: { patient_id: '2' ... } }

    更新

    在运行测试之前,您还需要在数据库中创建Dentist 记录。为此,请在您的测试用例中添加如下内容:

    describe 'POST #create' do
      before { Dentist.create!(id: 1) }
    
      it 'assigns a newly created appointment as @appointment' do
        post :create, { dentist_id: '1', appointment: { patient_id: '2', appt_date: '2015-12-05 09:00:00' } }
        ...
      end
    end
    

    【讨论】:

    • 我尝试了您的解决方案,现在收到以下错误:失败/错误:发布:创建,{牙医 ID:'16',约会:{患者 ID:'2',appt_date:'2015-12 -05 09:00:00' } } ActiveRecord::RecordNotFound: 找不到 'id'=16 的牙医
    • 您的测试数据库中有 ID 为 16 的牙医吗?
    • 这可能是因为 ID 为 16Dentist 记录不存在。更新了我的答案,包括在运行测试之前创建 Dentist 记录的说明。
    • 我不敢相信显而易见的事情逃脱了我。我能够通过测试。衷心感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 2021-03-14
    • 2018-01-30
    相关资源
    最近更新 更多