“[Class_Name]必须存在”rails 5 rspec测试关联

时间:2016-12-07 19:52:58

标签: ruby-on-rails ruby rspec ruby-on-rails-5 rspec-rails

在我的rails应用程序中,我有Service,Request和ServiceRequest模型。

关联是服务请求属于服务和请求。

使用rspec测试服务请求时,我有:

require "rails_helper"

describe Servicerequest, :type => :model do

  subject {
    described_class.new(userid: 'bbogus', status: 'new', request_id: 1, service_id: 3)
  }

  it "is valid with valid attributes"  do
    expect(subject).to be_valid
  end

  it "is not valid without a userid" do
    subject.userid = nil
    expect(subject).to_not be_valid
  end

  it "is not valid without a status" do
    subject.status = nil
    expect(subject).to_not be_valid
  end

  it "is not valid without a request_id" do
    subject.request_id = nil
    expect(subject).to_not be_valid
  end

  it "is not valid without a service_id" do
    subject.service_id = nil
    expect(subject).to_not be_valid
  end

  it { should belong_to(:request)}
  it { should belong_to(:service)}
end

并在servicerequest模型中:

class Servicerequest < ApplicationRecord
  validates_presence_of :userid, :status, :request_id, :service_id

  belongs_to :request, class_name: "Request"
  belongs_to :service, class_name: "Service"
end

出于某种原因,我的测试因此声明而失败:

1) Servicerequest is valid with valid attributes
  Failure/Error: expect(subject).to be_valid
    expected #<Servicerequest id: nil, created_at: nil, updated_at: nil, userid: "bbogus", status: true, request_id: 1, service_id: 3> to be valid, but got errors: Request must exist, Service must exist
  # ./spec/models/servicerequest_spec.rb:10:in `block (2 levels) in <top (required)>'

如何让我的测试通过Request must exist. Service must exist.部分?

1 个答案:

答案 0 :(得分:3)

您的规范指定了$(document).ready(function() { $('.dropDown').val(beginTime); } @foreach (var l in Model.Cleaner.TimeAvailables) { <select class="form-control dropDown" name="Sunday1From"> <option value="@l.BegginingTime" selected>@l.BegginingTime</option> <option value="00:00:00">12:00 AM</option> <option value="00:30:00">12:30 AM</option> <option value="01:00:00">1:00 AM</option> <option value="01:30:00">1:30 AM</option> <option value="02:00:00">2:00 AM</option> <option value="02:30:00">2:30 AM</option> </select> 的ID:

service_id

但这些不对应于数据库中实际存储的服务/请求模型 - 即没有id为3的Service或ID为1的Request。这是错误消息所指的内容。

您实际上也可以创建这些,然后消息就会消失。 例如:

request_id