ruby-on-rails - "[Class_Name] must exist"rails 5 rspec 测试协会

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

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

关联是这样的,servicerequests belong_to both Service and Request。

当用 rspec 测试 servicerequests 时,我有这个:

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

在服务请求模型中:

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)>'

如何让我的测试通过 请求必须存在。服务必须存在。部分?

最佳答案

您的规范在此处指定了 service_idrequest_id 的 ID:

request_id: 1, service_id: 3

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

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

let(:service) { Service.create(<valid service params go here>) }
let(:request) { Request.create(<valid request params go here>) }
subject {
  described_class.new(userid: 'bbogus', status: 'new', request_id: request.id, service_id: service.id)
}

关于ruby-on-rails - "[Class_Name] must exist"rails 5 rspec 测试协会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41026168/

相关文章:

ruby-on-rails - 工厂女孩 : How do define a factory without passing parameters

ruby-on-rails - rails 3 : Generate unique codes (coupons)

java - Ruby web 开发的良好框架

ruby-on-rails - 使用 rspec 通过正则表达式检查标签的属性

ruby-on-rails - Bootstrap javascript 在测试中有效,但在生产中无效?

ruby-on-rails - 有没有替代 Django 的 Rails Assets 管道?

ruby - 在 ruby​​ 中使用 PortAudio 包装器将声音录制到 .wav

ruby-on-rails-3 - RoutingError 与 RSpec Controller 对作用域路由进行测试

ruby - 如何在 PORO 中使用 RSpec 期望

ruby-on-rails - Rails - 双向 "friendship"模型(续)