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

I want to configure active_record_spec_helper for my Rails tests so that I can test my models without tuning the entire Rails environment, as Corey Haines put it in his excellent blog post on the topic .

(I know that preloaders, such as Spring or Guard, are part of the way to fix this problem, but I agree with Corey's argument that this is "really just a strip of help on the real problem.")

So, I set up my helper helper and other files as stated in Corey's blog post and this GitHub gist - but my problem is that I describe this in my comment on the same issue:

Basically, the associations between my models mean that in order to test one model I have to require so many other model files that in the first place it negates the use of active_record_spec_helper .

eg. if I want to test comment.rb , but my comment belongs_to :post , then to run my tests I need post as well as comment . But then post may have other associations, for example. belongs_to :user; has_many :drafts belongs_to :user; has_many :drafts , so I need to require user and drafts , and just check the comment ... then user and drafts also have associations, and so on, until I load almost every model in the diagram of my class.

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

Can I get around this and avoid require all these extraneous model files? Or is there something conceptual that I am missing - should I avoid linking all my models in this gigantic network, or is this inevitable?

Or is it just not worth the effort, and I have to stick with rails_helper loading the whole environment?

+6
source share
2 answers

I don’t think that you are missing something conceptual, and I think that models connected in the gigantic Internet through associations are natural in large Rails applications.

As for workarounds for this problem, I can think of a few:

  • Complete models that depend on testing models that directly depend on them. This saves you from having to download or plug in models that are indirectly dependent on.

  • Enable autoload. Although this will slow things down, it’s not the same as starting all Rails

  • Instead of simply listing your dependencies as comments at the top of your models, as Corey suggested, express them in Ruby code. This code may not work in production, but in the test you can configure the code to either require or drown the dependencies as you wish.

+2
source

I was able to solve this problem using FactoryGirl. Please see my article for details .

Using factory_girl_require_helper.rb , you can do something like this at the top of the test:

 require_factory_and_model_for(:comment) 

This will automatically load any related models that depend on the Comment based on the factory that you defined for it.

0
source

Source: https://habr.com/ru/post/979462/


All Articles