assert_difference('Course.count') expects difference but there is no change
<p>I'm running a test to try to add a course to my database, but for some reason it doesn't seem to be adding since when I run:</p>

<pre><code>test "should create course" do
    assert_difference('Course.count') do
      post :create, course: { name: 'New',
                              course_code: '1' }
    end

    assert_redirected_to course_path(assigns(:course))
  end
</code></pre>

<p>I get:</p>

<pre><code>"Course.count" didn't change by 1.
&lt;3&gt; expected but was
&lt;2&gt;.
</code></pre>

<p>What's weird is that when I run the rails console and do </p>

<pre><code>@course = Course.new(name: 'New', course_code: '1')
@course.save 
</code></pre>

<p>the course saves correctly in the database. </p>

<p>Here is the code for the create action:</p>

<pre><code>def create

    @course = Course.new(params[:course])

    respond_to do |format|
      if @course.save
        @registration = Registration.new
        @registration.active = true
        @registration.user = current_user
        @registration.course = @course
        @registration.course_code = @course.course_code
        @registration.instructor = true
        @registration.save!
        admin = User.find_by_email('admin@email.com')
        @registration = Registration.new
        @registration.active = true
        @registration.user = admin
        @registration.course = @course
        @registration.course_code = @course.course_code
        @registration.instructor = true
        @registration.save!

        format.html { redirect_to @course }
        format.json { render json: @course, status: :created, location: @course }
      else
        format.html { render action: "new" }
        format.json { render json: @course.errors, status: :unprocessable_entity }
      end
    end
  end
</code></pre>

<p>Here is the relevant model code for the Course model:</p>

<pre><code>class Course &lt; ActiveRecord::Base
  before_create :create_unique_identifier
  attr_accessible :name, :course_code

  # Relationships
  has_many :registrations, dependent: :destroy
  has_many :assignments, dependent: :destroy
  has_many :users, :through =&gt; :registrations

  def create_unique_identifier
    begin
      self.course_code = SecureRandom.hex(4)
    end while self.class.exists?(:course_code =&gt; course_code)
  end
</code></pre>

<p>Does anyone know why I might be getting this error?</p>