首页 > 解决方案 > ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE 约束失败:rooms.number

问题描述

有人可以帮我解决这个问题吗?这是我使用 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

Schema -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

非常感谢您!

标签: ruby-on-rails-5

解决方案


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


推荐阅读