title: Stubbing model attributes in controller tests
body: <p>I am finding it very hard to stub certain attributes of a model on a controller test. I want to make sure to stub as little as possible. </p>
  
  <hr>
  
  <p><strong>EDIT</strong>: I have been demoved of using stubs for such integration. I understood that the stubs won't reach the action call. The correct question would now be:</p>
  
  <blockquote>
    <p>How can one use mocks and stubs to simulate a certain state in a Rails controller test?</p>
  </blockquote>
  
  <hr>
  
  <p>So I've reached something like the following:</p>
  
  <h2>Spec</h2>
  
  <pre class="lang-rb prettyprint-override"><code>require 'spec_helper'
  
  describe TeamsController do
    let(:team) { FactoryGirl.create :team }
  
    context "having questions" do
      let(:competition) { FactoryGirl.create :competition }
  
      it "allows a team to enter a competition" do
        post(:enter_competition, id: team.id, competition_id: competition.id)
  
        assigns(:enroll).team.should == team
        assigns(:enroll).competition.should == competition
      end
    end
  
    # ...
  end
  </code></pre>
  
  <h2>Factories</h2>
  
  <pre class="lang-rb prettyprint-override"><code>FactoryGirl.define do
    factory :team do
      name "Ruby team"
    end
  
    factory :competition, class: Competition do
      name "Competition with questions"
  
      after_create do |competition|
        competition.
          stub(:questions).
          and_return([ 
            "something"
          ])
      end
    end
  
    factory :empty_competition, class: Competition do
      name "Competition without questions"
      questions []
  
      after_create do |competition|
        competition.stub(:questions).and_return []
      end
    end
  end
  </code></pre>
  
  <h2>Production code</h2>
  
  <pre class="lang-rb prettyprint-override"><code>class TeamsController &lt; ApplicationController
    def enter_competition
      @team = Team.find params[:id]
      @competition = Competition.find params[:competition_id]
      @enroll = @team.enter_competition @competition
  
      render :nothing =&gt; true
    end
  end
  
  class Team &lt; ActiveRecord::Base
    def enter_competition competition
      raise Competition::Closed if competition.questions.empty?
  
      enroll = Enroll.new team: self, competition: competition
      enroll.save
      enroll
    end
  end
  </code></pre>
  
  <p>When I run the test, the <code>questions</code> attribute comes as being <code>nil</code> and so the test fails in the model when checking for <code>nil.empty?</code>.</p>
  
  <p>Why isn't the stub being used so that the state of that message is correctly used? I expected that <code>@competition.questions</code> would be <code>[ "question" ]</code> but instead I get <code>nil</code>.</p>