[rspec-devel] Fwd: [ rspec-Bugs-6905 ] Mocking rails associations where the association is validated

Pat Maddox pergesu at gmail.com
Mon Nov 27 04:29:27 EST 2006

On 11/26/06, David Chelimsky <dchelimsky at gmail.com> wrote:
> This could be solved by
> adding an add_person method to User. Now your controller spec could
> look like this:
> specify "should create a new Person and stick it in the users people" do
>   mock_user = mock("user")
>   mock_person = mock("person")
>   mock_user.should_receive(:add_person).with(mock_person)
>   User.should_receive(:find_by_login).with("pat").and_return(mock_user)
>   Person.should_receive(:new).with(:name => "BJ").and_return(mock_person)
>   post :create, :user_id => "pat", :person => { :name => "BJ" }
> end

If I want to specify the redirect, would I do

  specify "should redirect to the new person" do
    mock_user = mock("user", :null_object => true)
    mock_person = mock("person")


    Person.should_receive(:new).with("name" => "BJ").and_return(mock_person)

    controller.should_redirect_to :action => "show", :user_id => "pat",
                                  :id => 1
    post :create, :user_id => "pat", :person => { :name => "BJ" }

or should I just include the controller.should_redirect_to in the
first spec I showed?  I try to stick to Dave Astels' "One Expectation
Per Example" guideline...and I usually do fine when writing model
code, or standalone classes, but obviously neither of these examples
follows that at all closely.  Is it even possible to follow it with
controller specs?  I'm trying to get some heuristics for determining
how much is too much in a single spec.

In my example, redirecting behavior doesn't have anything to do with
the behavior of adding a user, so I think they should be split out.
But then there's a lot of code in the second spec that has nothing to
do with the redirect behavior (User.find and Person.new certainly
don't have anything to do with that).  Is that just a consequence of
all that goes on in an action, or is it a sign that there's room to


More information about the rspec-devel mailing list