Testing Rails module without loading ActiveRecord

孤者浪人 提交于 2020-01-04 11:10:08

问题


I'm working on a Rails app which I am testing with RSpec. After a lot of waiting for tests to finish, I've followed Gary Bernhardt's advice and this informative post by Paul Annesley and setup a tiered spec_helper where I only load what parts of Rails I absolutely need, to keep test times down, and extract functionality into separate modules which I test in isolation.

This is working up to a point. The problem is that I have a module (extending ActiveSupport::Concern) with instance and class methods that build on ActiveRecord functionality, e.g. tying in to dynamic finders like find_and_create_by_. So far I've been able to just create a dummy class which includes the module and test on that, but now I'd like to move more logic from my ActiveRecord model into the module.

Concrete examples would be stuff like callbacks, validators, and method delegation, all of which are related by the fact that they relate to an API I'm accessing.

I'm stuck now though with two choices in my tests:

  1. stub and/or mock every ActiveRecord method that I call in the module, which would keep the tests fast but potentially make the test code very complex, or
  2. require activerecord in the test, make my dummy class inherit from ActiveRecord::Base and just test the module as I would test any other rails model, which would be slower but keep the test code clean.

The latter option doesn't really appeal to me, since the whole reason I'm isolating the code in a module is that I want to separate it from Rails. I'm not looking for a black or white answer here, but would anyone have any advice or pointers to best practices on this situation? Thanks very much in advance!


回答1:


Option 1 seems tantalizing, but is fraught with peril IMHO. The scope of the mocking and stubbing that you would need to do is much like one of Rumsfeld's proverbial "unknown unknowns". Would you eventually end up stubbing out all of ActiveRecord?

Even if you could make it it work, would it tolerate future changes in ActiveRecord? Would you have to update your mocks/stubs to keep up with new versions?

I would love to see a mocking library that can substitute ActiveModel/ActiveRecord for this very purpose. I'd say though that unless you have tolerance for spending what could end up being a lot of time building such a thing, that you're better off going with option 2.




回答2:


The solution which works for me for speed up my testing process is by combining spork and guard, guard is actually to watch and run the tests but it will make your process speed.

I dont have a proper write up, but you could refer this gist on setting up the spork with guard

and these are the resources I used

guard

spork

HTH



来源:https://stackoverflow.com/questions/14228851/testing-rails-module-without-loading-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!