title: Rspec Rails: testing controller method 'create' with a multi-model form
body: <p>I am building a Ruby on Rails app with the usual assortment of models, views and controllers.</p>
  
  <p>The 'create' action in one of my controllers is supposed to create an instance of two different models.  Here's my code:</p>
  
  <pre><code> def create
    @league = League.new(params[:league])
    @user = @league.users.build(params[:user])
    ... .save conditions appended ...
   end
  </code></pre>
  
  <p>So, when you call 'create' through the LeaguesController via a POST request to /leagues, you get a new instance of League and a new instance of User.  I also want the new User instance to inherit the ID of the new League instance, so it can be used as the foreign key to link the instances together.  This is accomplished with:</p>
  
  <pre><code> def create
    @league = League.new(params[:league])
    @user = @league.users.build(params[:user])
    @league_id = @league.id
    @user.update_attribute('league_id', @league_id)
    ... .save conditions appended ...
   end
  </code></pre>
  
  <p>The User model already <code>belongs_to</code> the League model, which <code>has_many</code> users.  </p>
  
  <p>The above code works just fine and dandy, verified via manual testing.  However, I can't for the life of me figure out how to automate these tests with Rspec.  I'm trying to be a good boy and use test-driven design, but this has me stumped.  </p>
  
  <p>The issue is that I can't figure out how to access the attributes of the newly created instances of League and User in my tests.  I am attempting to do so using the following code:</p>
  
  <pre><code>describe LeaguesController do
    describe 'new league and user' do
      it 'should create a new user with a league_id equal to the new leagues id'
        @league_attr = { :name =&gt; "myleague", :confirmation_code =&gt; "mycode", :id =&gt; 5}
        @user_attr = { :username =&gt; "myname", :password =&gt; "mypass"}
        post :create, :user =&gt; @user_attr, :league =&gt; @league_attr
        assigns(:league_id).should eql(5)
      end
    end
  end
  </code></pre>
  
  <p>But the test returns <code>nil</code> for the value of <code>:league_id</code></p>
  
  <p>I'm new to both programming in general and Rspec in particular, so I really appreciate any help someone might offer!  </p>