Fixtures, mock objects or in-memory ActiveRecord objects?

Posted by James Mead Sat, 23 Dec 2006 20:00:00 GMT

Wilson Bilkovich has posted an article about mocking ActiveRecord objects.

A new method mock_model is defined that builds a mock object which will respond the same way as a real ActiveRecord object. As I understand it, this means he can replace…

  @campaign = mock("campaign")
  @campaign.stub!(:is_a?).and_return(true)
  @campaign.stub!(:new_record?).and_return(false)
  @campaign.stub!(:id).and_return(rand(1000))

with…

  mock_model :campaign

Although I agree with him that using fixtures is not a good idea, why not use a real ActiveRecord object…

  @campaign = Campaign.new

Sometimes due to the way ActiveRecord couples your models to the database, it becomes essential to have a model in the database and not just in memory. In which case why not just do this…

  @campaign = Campaign.create!

I’ve written up a couple more thoughts here and here.

Tags , , , , , ,  | 1 comment

Comments

  1. David Chelimsky said 2 days later:

    I think this depends on what the test is about. If testing controllers and views, I never want to hit the database. This is somewhat aside from the meaning of mocks as described by the OOPSLA paper on mock objects. Really, what we’re doing is using the mock framework to create something like a mock, something like a stub, to stub out a specific object. The benefit is fast running tests!

    For that reason I’d like to avoid the database entirely for some model tests as well. Jay Fields talks a lot about that on his blog.

Comments are disabled