Skip to content

Instantly share code, notes, and snippets.

@koffeinfrei
Last active March 6, 2016 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koffeinfrei/7834fce1a5b7b995b412 to your computer and use it in GitHub Desktop.
Save koffeinfrei/7834fce1a5b7b995b412 to your computer and use it in GitHub Desktop.
has_many dependent spec
# File: spec/models/base_spec.rb
require 'rails_helper'
RSpec.describe 'All ActiveRecord::Base models' do
context 'has_many with :dependent key' do
each_active_record_model do |model|
has_many_relations(model).each do |has_many_relation|
it "has :dependent defined on the #{model}##{has_many_relation.name} relation" do
expect(has_many_relation.options[:dependent]).not_to be_nil
end
end
end
end
end
# File: spec/support/active_record_helper.rb
# Yields a block for each of our defined
# active record models
def each_active_record_model(&block)
# eagerly require all the models in order to have them all available
Dir["#{Rails.root}/app/models/**/*.rb"].each { |file| require file }
ActiveRecord::Base.subclasses
.reject { |type| type.to_s.include? '::' } # subclassed classes are not our own models
.each(&block)
end
# Returns all `has_many` relations of the model, excluding
# the `has_many :through` ones.
def has_many_relations(model)
model
.reflect_on_all_associations(:has_many)
.reject { |relation| relation.options[:through] }
end
# Console output of `rspec spec/models/base_spec.rb --format d`
All ActiveRecord::Base models
has_many with :dependent key
has :dependent defined on the User#comments relation
has :dependent defined on the User#articles relation
has :dependent defined on the User#likes relation
has :dependent defined on the User#votes relation (FAILED - 1)
Failures:
1) All ActiveRecord::Base models has_many with :dependent key has :dependent defined on the User#votes relation
Failure/Error: expect(has_many_relation.options[:dependent]).not_to be_nil
expected: not nil
got: nil
# ./spec/models/base_spec.rb:8:in `block (5 levels) in <top (required)>'
# ./spec/rails_helper.rb:61:in `block (3 levels) in <top (required)>'
# ./spec/rails_helper.rb:60:in `block (2 levels) in <top (required)>'
# File: spec/rails_helper.rb
# ...
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment