active-hash/active_hash

Error: Undefined method `reflect_on_association' for Category:Class

Closed this issue · 2 comments

app/models/category.rb

class Category < ActiveYaml::Base
  include ActiveHash::Associations

  has_many :products
end

app/models/product.rb

class Product < ActiveRecord::Base
  extend ActiveHash::Associations::ActiveRecordExtensions

  belongs_to_active_hash :category
end

spec/models/category_spec.rb

require 'rails_helper'

RSpec.describe Category, type: :model do
  describe "Associations" do
      if { should have_many(:products) }
  end
end

When I run rspec spec/models/category_spec.rb, I got the below error:

Failure/Error: should have_many(:products)
     
     NoMethodError:
       undefined method 'reflect_on_association' for Category:Class
     # /bundle/gems/active_hash-2.2.0/lib/active_hash/base.rb:324:in 'method_missing'
     # /bundle/gems/active_hash-2.2.0/lib/active_file/base.rb:52:in 'block (2 levels) in singleton class'
     # /bundle/gems/shoulda-matchers-3.1.2/lib/shoulda/matchers/active_record/association_matchers/model_reflector.rb:21:in 'reflect_on_association'
     # /bundle/gems/shoulda-matchers-3.1.2/lib/shoulda/matchers/active_record/association_matchers/model_reflector.rb:17:in 'reflection'
     # /bundle/gems/shoulda-matchers-3.1.2/lib/shoulda/matchers/active_record/association_matcher.rb:883:in 'reflection'
     # /bundle/gems/shoulda-matchers-3.1.2/lib/shoulda/matchers/active_record/association_matcher.rb:1060:in 'association_exists?'
     # /bundle/gems/shoulda-matchers-3.1.2/lib/shoulda/matchers/active_record/association_matcher.rb:989:in 'matches?'

Please let me know what's wrong? Thanks in advance.

@ducnguyenhuy Hi. Thanks for using this gem.
It seems that shoulda-matchers expects #reflect_on_association is defined for subject class, but ActiveHash isn't.
Unfortunately ActiveHash doesn't support full of ActiveRecord's interface.
Please try to test it other way. (e.g. Does Category#products return instance of ActiveRecord::Relation or not)

If you are interested in enhancement of ActiveHash behavior, PR is welcome!

@syguer Thanks for reply. Yes, I'm trying as below. It works but it does not look like the way I often do spec for models :)

before { @category = build(:category) }
it 'has many products' do
   expect(@category.products).not_to be_nil
end