Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

requiring an ActiveRecord model without having to require the entire class diagram, for active_record_spec_helper

I want to set up an active_record_spec_helper for my Rails tests so that I can test my models without having to set up the entire Rails environment - as laid out by Corey Haines in his excellent blog post on the subject.

(I know that preloaders like Spring or Guard go part of the way towards fixing this problem, but I agree with Corey's argument that this is "really just a band-aid over the real problem".)

So I've set up my spec helper and other files as laid out in Corey's blog post and this GitHub gist - but my problem is exactly as I describe it in my comment on that same gist:

Basically, the associations between my models mean that to test a single model, I have to require so many other model files that it negates the point of using active_record_spec_helper in the first place.

E.g. if I want to test comment.rb but my comment belongs_to :post, then I have to require post as well as comment to make my tests work. But then Post may have other associations, e.g. belongs_to :user; has_many :drafts, so I have to require user and drafts as well just to test Comment... then user and drafts have associations too, and so on until I end up loading practically every model in my class diagram.

(If this doesn't make sense, I gave a more detailed explanation in the comment.)

Is it possible to work around this and avoid having to require all those extraneous model files? Or is there something conceptual that I'm missing - should I be avoiding linking all my models in this giant web, or is it unavoidable?

Or is it just not worth the effort and should I stick with letting rails_helper load the whole environment?

like image 1000
GMA Avatar asked Dec 11 '14 15:12

GMA


1 Answers

I don't think you're missing anything conceptual and I think having models linked in a giant web through associations is natural in large Rails applications.

As for workarounds to this problem, I can think of several:

  • Stub the models being depended on when testing the models that directly depend on them. This will eliminate the need to load or stub the models indirectly depended on.

  • Turn on autoloading. While this will slow things down, it's not the same as starting up all of Rails

  • Instead of just listing your dependencies as comments at the top of your models as Corey suggested, express them in Ruby code. This code can be a no-op in production, but in test you can configure the code to either require or stub the dependencies as you wish.

like image 113
Peter Alfvin Avatar answered Oct 18 '22 05:10

Peter Alfvin