Let's say I have 3 records in SampleModel:
I have a controller action that should only return records that were
created after 6/3/2007. I can see how to do it with fixtures, but can I
perform this type of test with a mock object and/or stubs?
There's really two parts to this - how would you do it using mocks,
and what exactly would you mock? If it were me, it would look like
this (using rspec, but you can do the same thing w/ test/unit+mocha or
describe SampleModelsController, "handling GET /date_filtered_action" do
it "should ask SampleModel for items created before the submitted date" do
get "date_filtered_action", :cutoff => "6/22/2007"
class SampleModelsController < Application
@sampleModels = SampleModel.find_created_before(params[:cutoff])
And then I'd test the find_created_before method in my description of
SampleModel's behaviour (TestSampleModel if you're using test/unit).
Now if you want to use mocks in the model test as well, you could do this:
describe SampleModel do
it "should provide items created before a submitted date" do
SampleModel.should_receive(:find).with(:conditions => ["created_at
class SampleModel < ActiveRecord::Base
self.find(:all, :conditions => ["created_at > ?",
Note that this sort of testing is very risky if you're not also doing
integration testing of some sort. For example, this would pass even if
there was no created_at column in the sample_models table. I happen to
do a lot of this sort of testing, but I do it in concert with customer
acceptance tests (i.e. high level end-to-end tests).
Hope that helps.
ps - I didn't run this, so please forgive any errors.