[rspec-users] isolating controller tests from models

Justin Ko jko170 at gmail.com
Sat Mar 31 05:49:03 UTC 2012


On Mar 30, 2012, at 11:11 PM, Fearless Fool wrote:

> This is a rehash of a question I posed at:
> http://stackoverflow.com/questions/9952317/isolating-controller-tests-from-models
> The basic question: If I have a FoosController and a Foo model, can I
> run FoosController rspec tests without creating the foos database table?
> I haven't found a good way to avoid it.
> 
> Consider this simple controller:
> 
>   # file: app/controllers/foos_controller.rb
>   class FoosController < ApplicationController
>     respond_to :json
>     def create
>       @foo = Foo.create(params[:foo])
>       respond_with @foo
>     end
>   end
> 
> In my RSpec tests, I can do
> 
>   @foo = mock_model("Foo")
>   Foo.stub(:create) { @foo }
>   post :create, :format => :json
> 
> ... but that fails in the call to respond_with @foo, because
> ActionController calls @foo.has_errors? which in turn hits the database
> to look up column names.  I could stub out has_errors?, but that means
> that I'm reaching into the internals of the system -- probably not a
> good idea for a test suite.

Oh, the irony!

You're using rspec-rails, which reaches *much further* into the "system" than `has_errors?`.

Mucking with a non-public API is not a "never ever" thing :)

> 
> If the answer to my question "can I do controller testing without
> creating the underlying database tables?" is 'no', then I'll accept that
> (with regret).  But I'd rather hear that it is somehow possible.
> 
> - ff
> 
> -- 
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users



More information about the rspec-users mailing list