本文介绍了应该使用 Rspec Gem 返回“String:Class 的未定义方法‘reflect_on_association’"在属于测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 rails 应用程序中,我有我的模型 RequestServiceServiceRequest

In my rails app, I have my models Request, Service, and ServiceRequest

在我的 models.rb 文件中:

In my models.rb files I have:

request.rb:

class Request < ApplicationRecord

  validates_presence_of :userid, :supervisor, :status 

  has_many :servicerequests, dependent: :destroy
  accepts_nested_attributes_for :servicerequests

end

service.rb:

class Service < ApplicationRecord
  validates_presence_of :title, :responsible

  has_many :servicerequests, dependent: :destroy
end

servicerequest.rb:

class Servicerequest < ApplicationRecord
  belongs_to :request, optional: true
  belongs_to :service, optional: true
end

以及导致问题的规范servicerequest_spec.rb:

require "rails_helper"

describe "ServiceRequests", :type => :model do 
  it "is valid with valid attributes"
  it "is not valid without a userid"
  it "is not valid without a request_id"
  it "is not valid without a service_id"

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

特别是这两行:

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

我收到错误:

     NoMethodError:
   undefined method `reflect_on_association' for String:Class
 # /Users/criva/.rvm/gems/ruby-2.3.1@onboard/gems/shoulda-matchers-2.8.0/lib/shoulda/matchers/active_record/association_matchers/model_reflector.rb:21:in `reflect_on_association'
 # /Users/criva/.rvm/gems/ruby-2.3.1@onboard/gems/shoulda-matchers-2.8.0/lib/shoulda/matchers/active_record/association_matchers/model_reflector.rb:17:in `reflection'
 # /Users/criva/.rvm/gems/ruby-2.3.1@onboard/gems/shoulda-matchers-2.8.0/lib/shoulda/matchers/active_record/association_matcher.rb:825:in `reflection'
 # /Users/criva/.rvm/gems/ruby-2.3.1@onboard/gems/shoulda-matchers-2.8.0/lib/shoulda/matchers/active_record/association_matcher.rb:993:in `association_exists?'
 # /Users/criva/.rvm/gems/ruby-2.3.1@onboard/gems/shoulda-matchers-2.8.0/lib/shoulda/matchers/active_record/association_matcher.rb:926:in `matches?'
 # ./spec/models/servicerequest_spec.rb:10:in `block (2 levels) in <top (required)>'

我意识到 shoulda 还没有内置 optional ,但我想找出一种方法来测试它,但仍将其保留在那里.

I realize that shoulda doesn't have optional built in yet, but I wish to figure out a way to test it, yet keep it there.

任何帮助都有助于解决这个谜团.

Any help would be great in solving this mistery.

我已经尝试过 it { should own_to(:request).optional(true)}it { should own_to(:request).conditions(optional: true)} 无济于事.

I have attempted it { should belong_to(:request).optional(true)} and it { should belong_to(:request).conditions(optional: true)} to no avail.

推荐答案

感谢@Aguardientico 指出,我应该把

Thanks to @Aguardientico for pointing out, I should have put

describe ServiceRequest 而不是 describe "ServiceRequests"

这篇关于应该使用 Rspec Gem 返回“String:Class 的未定义方法‘reflect_on_association’"在属于测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 08:54