Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Shoulda-matchers belong_to optional test

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.

like image 722
meerkat Avatar asked Jan 09 '19 16:01

meerkat


2 Answers

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

like image 120
shilovk Avatar answered Nov 09 '22 11:11

shilovk


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
like image 19
Michael Arkhipov Avatar answered Nov 09 '22 09:11

Michael Arkhipov