RSpec ActiveRecord :: RecordNotFound

时间:2015-12-04 04:53:46

标签: ruby-on-rails ruby activerecord rspec

我很难通过测试:

错误:

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

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

1 个答案:

答案 0 :(得分:1)

在您的请求中,您正在执行if(inProduction){ //include some code for production }else{ //include some code for development } ,这意味着您的控制器中的let ifActiveQuery = PFQuery(className: "Vaccine") ifActiveQuery.whereKey("userID", equalTo: self.userID) ifActiveQuery.whereKey("vaccineType", equalTo: self.vaccineDocument) ifActiveQuery.getFirstObjectInBackgroundWithBlock({ (objects, error) -> Void in objects?.deleteInBackground() print("deleted object: \(objects)") } let ifNonExistQuery = PFQuery(className: "Vaccine") ifNonExistQuery.whereKey("userID", equalTo: self.userID) ifNonExistQuery.whereKey("vaccineType", equalTo: self.vaccineDocument) ifNonExistQuery.getFirstObjectInBackgroundWithBlock { (objects, error) -> Void in postImage.saveInBackgroundWithBlock { (succeeded: Bool, error: NSError?) -> Void in self.activityIndicator.stopAnimating() UIApplication.sharedApplication().endIgnoringInteractionEvents() print("Saved new object \(postImage)") print("Saved new object:\(self.expirationField.text)") self.dismissViewControllerAnimated(true, completion: nil) self.expirationField.text = "" self.imageToPost.image = UIImage(named: "addDocument.jpg") } } 将为post :create, { appointment: { dentist_id: '1', ... } }(请注意您在params[:dentist_id]下嵌套nil 1}}在您的请求参数中)。要解决此问题,请将控制器操作中的dentist_id更改为appointment,或将请求更改为@dentist = Dentist.find(params[:dentist_id])

<强>更新

您还需要在运行测试之前在数据库中创建@dentist = Dentist.find(params[:appointment][:dentist_id])记录。为此,请在测试用例中添加以下内容:

post :create, { dentist_id: '1', appointment: { patient_id: '2' ... } }