How do you drown ActiveRecord :: Basic methods without making assumptions about how they are used?

ActiveRecord::Base has a large ol API with several methods for finding and saving objects. For example, your AR::B objects can be created from several methods:

  • Foo.new(…)
  • Foo.create(…)
  • Foo.find(…)
  • Foo.find_by_sql(…)
  • Foo.find_[all_]by_*(…)
  • bar.foos (associations)
    • ... and association search methods, of course

Similarly, the object in question can be saved in several different ways:

  • foo.create or foo.create!
  • foo.save or foo.save!
  • foo.update_attributes or foo.update_attributes!

Now, when writing unit tests, it’s good practice to drown out external method calls so that your test can focus on the business logic of the method in question. However, when it comes to working with AR::B objects - for example, in tests of a controller block - it seems that you need to fix one of the above methods, when in fact, regarding the business logic of the method, t be important, which you you take.

Do you need to associate the behavior of your method with its implementation, or am I missing something simple?

+8
ruby-on-rails activerecord unit-testing stubbing
source share
1 answer

One approach is to create your classes so that you complete any calls to the ActiveRecord::Base methods in your own methods.

Therefore, instead of directly calling Foo.new(…) ...

 class Foo < ActiveRecord::Base def self.create_object(…) new(…) end end 

Thus, in your tests, you can disable your own methods instead of ActiveRecord.

This approach (including its "benefits" is described in detail by Avdi Grimm in his book "Objects on rails" ... http://objectsonrails.com

+3
source share

All Articles