assert_difference('Course.count')期望差异,但没有变化

时间:2016-01-02 03:12:44

标签: ruby-on-rails ruby testing

我正在运行测试以尝试在我的数据库中添加一个课程,但由于某些原因它似乎没有添加,因为我运行时:

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

我明白了:

"Course.count" didn't change by 1.
<3> expected but was
<2>.

当我运行rails控制台并执行

时,有点奇怪
@course = Course.new(name: 'New', course_code: '1')
@course.save 

课程在数据库中正确保存。

以下是创建操作的代码:

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

以下是课程模型的相关型号代码:

class Course < 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 => :registrations

  def create_unique_identifier
    begin
      self.course_code = SecureRandom.hex(4)
    end while self.class.exists?(:course_code => course_code)
  end

有谁知道为什么我会收到此错误?

0 个答案:

没有答案