ruby-on-rails-5 - 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
非常感谢您!
解决方案
因此,由于某种原因,您已经有一个带有该号码的房间。我最好的猜测是@room
测试中使用的 ivar 已经持久化到数据库中。为了使测试通过,您应该尽可能避免依赖@room
或完全放弃它,而是通过您的选择。
推荐阅读
- laravel - 在 laravel + vue.js 中使用 v-for,我试图显示一个包含用户信息的表格,但没有显示
- javascript - ReferenceError: require is not defined @react
- asp.net-core - ADFS 通过 OIDC 作为 IdentityServer4 的外部身份提供者
- oauth-2.0 - Oauth2 与 Postman 和 IdentityServer4
- node.js - Nodejs 流链承诺只写第一个
- python - Remove comma only from number separators (regular expression grouping)
- apache-flink - How to write outer join function in Flink using connect?
- java - 测试响应式存储库 java.lang.AssertionError:期望“assertNext”失败(期望:onNext();实际:onComplete())
- django - Django, exclude from main list, but viewable from django filter
- javascript - 引导模式 - 不要禁用页面