Rails: Shoulda-matchers belong_to optional test
Asked Answered
C

2

23

I have a model

class Certificate < ApplicationRecord
  notification_object
  belongs_to :user
  belongs_to :share_class, optional: true
  belongs_to :round, optional: true
  belongs_to :company, optional: true
  has_many :approvals, as: :votable
end

The spec for this model looks like this

require 'rails_helper'

RSpec.describe Certificate, type: :model do
  it { should belong_to(:user) } 
  it { should belong_to(:share_class).optional } 
  it { should belong_to(:round).optional } 
  it { should belong_to(:company).optional } 
  it { should have_many(:approvals) } 
end

But when I run this spec I get this error

1) Certificate is expected to belong to share_class optional: true

     Failure/Error: it { should belong_to(:share_class).optional }
       Expected Certificate to have a belongs_to association called share_class (the association should have been defined with`optional: true`, but was not)
     # ./spec/models/certificate_spec.rb:5:in `block (2 levels) in <top (required)>'

I do not know why I'm getting this error.

Chesterton answered 9/1, 2019 at 16:26 Comment(2)
do the other optional specs pass?Viperine
@Viperine Yes it does that's why its confusing to meChesterton
P
25

For the first, you should read this conversation.

@mcmire We have a pre-release version out now! Try v4.0.0.rc1 to get optional.

And then, the expected code should look like this:

RSpec.describe Certificate, type: :model do
  it { should belong_to(:user) } 
  it { should belong_to(:share_class).optional } 
  it { should belong_to(:round).optional } 
  it { should belong_to(:company).optional } 
  it { should have_many(:approvals) } 
end
Purplish answered 9/1, 2019 at 17:59 Comment(4)
Are you sure? I don't think optional method accepts any arguments either on master and 4.0.0 github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/… github.com/thoughtbot/shoulda-matchers/blob/v4.0.0.rc1/lib/…Sugihara
@Sugihara As you can see, I quoted the creator of the shoulda-matchers (@mcmire). And yes. I'm sure those words correct. P.s. v4.0.0.rc1Purplish
@MichaelArkhipov I have the pre - release version but its not working on that. Also the belong_to round and belong_to company tests are running fine so I don't know whats wrong with the first oneChesterton
optional does not take an argument (anymore?) github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/… so it is just should belong_to(:something).optionalNoncommittal
P
6
class Person < ActiveRecord::Base
  belongs_to :organization, optional: true
end

# RSpec
describe Person
  it { should belong_to(:organization).optional }
end

# Minitest (Shoulda)
class PersonTest < ActiveSupport::TestCase
  should belong_to(:organization).optional
end

Documentation

Paterfamilias answered 24/4, 2020 at 23:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.