应该用Rspec Gem返回"未定义的方法`reflect_on_association' for String:Class" in belongs_to test

时间:2016-11-29 23:35:17

标签: ruby-on-rails testing rspec shoulda

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

在我的models.rb文件中,我有:

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

我意识到,还没有内置optional,但我希望找到一种方法来测试它,但保留它。

任何帮助都可以很好地解决这个问题。

我尝试it { should belong_to(:request).optional(true)}it { should belong_to(:request).conditions(optional: true)}无济于事。

1 个答案:

答案 0 :(得分:1)

感谢@Aguardientico指出,我应该放

describe ServiceRequest代替describe "ServiceRequests"

相关问题