ActiveRecord :: RecordNotUnique:SQLite3 :: ConstraintException:UNIQUE约束失败:rooms.number

时间:2018-09-04 14:16:33

标签: ruby-on-rails-5

有人可以帮我解决这个问题吗?这是我与Rails合作的第一周,我的所有测试都通过了,但下面的一个通过了。我了解这是由于独特的限制,但我不知道我还需要做什么。

    Error:
RoomsControllerTest#test_should_create_room:
ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: rooms.number: INSERT INTO "rooms" ("number", "capacity", "created_at", "updated_at") VALUES (?, ?, ?, ?)
    app/controllers/rooms_controller.rb:31:in `block in create'
    app/controllers/rooms_controller.rb:30:in `create'
    test/controllers/rooms_controller_test.rb:20:in `block (2 levels) in <class:RoomsControllerTest>'
    test/controllers/rooms_controller_test.rb:19:in `block in <class:RoomsControllerTest>'

这是rooms_controller中的创建方法:

def create
    @room = Room.new(room_params)

    respond_to do |format|
      if @room.save
        format.html { redirect_to rooms_path, notice: 'Room was successfully created.' }
        format.json { render :show, status: :created, location: @room }
      else
        format.html { render :new }
        format.json { render json: @room.errors, status: :unprocessable_entity }
      end
    end
  end

这是测试本身:

  test "should create room" do
    assert_difference('Room.count') do
      post rooms_url, params: { room: { capacity: @room.capacity, number: @room.number } }
    end

    assert_redirected_to rooms_url
  end

模式-unique:true,因此不会重复添加相同的数字:

  create_table "rooms", force: :cascade do |t|
    t.integer "number"
    t.integer "capacity"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["number"], name: "index_rooms_on_number", unique: true
  end

我使用以下命令重置测试数据库:

bundle exec rake db:drop RAILS_ENV=test
bundle exec rake db:create RAILS_ENV=test

非常感谢您!

1 个答案:

答案 0 :(得分:0)

因此由于某种原因,您已经有一个带有该号码的房间。我最好的猜测是,测试中使用的@room ivar已经保存在数据库中了。要使测试通过,您可能应该避免依赖@room或尽可能放弃它,而应通过许多选择。