【发布时间】:2018-04-21 22:16:51
【问题描述】:
在我将 Note 表切换为使用 UUID 之前,我已经通过了这个测试:
test "SHOULD create note AND redirect to Notes#index(SINCE null folder_id) WHEN only body is provided IF logged in as account:owner" do
sign_in @user
assert_difference('@user.account.notes.count') do
post notes_url(@user.account.hash_id), params: { note: { body: @note_by_user_no_folder.body } }
end
assert_redirected_to notes_url(@user.account.hash_id, anchor: Note.last.id)
end
但切换到 UUID 后,出现以下失败错误:
Failure:
NotesControllerTest#test_SHOULD_create_note_AND_redirect_to_Notes#index(SINCE_null_folder_id)_WHEN_only_body_is_provided_IF_logged_in_as_account:owner [/Users/chris/Dropbox/Repositories/keepshelf/test/controllers/notes_controller_test.rb:117]:
Expected response to be a redirect to <http://www.example.com/11111111/notes#9dc409ff-14cc-5f64-8f5f-08e487f583ee> but was a redirect to <http://www.example.com/11111111/notes#34dac6b7-46af-4c5c-bff7-760ffa77edf6>.
Expected "http://www.example.com/11111111/notes#9dc409ff-14cc-5f64-8f5f-08e487f583ee" to be === "http://www.example.com/11111111/notes#34dac6b7-46af-4c5c-bff7-760ffa77edf6".
我认为这是因为 UUID 不遵循命令,所以我在“post notes_url(...”中创建的新注释最终不会成为 Note.last.id 找到的“最后一个”。
如何将锚:设置为record_that_was_just_created.id?
【问题讨论】:
-
您可以尝试使用
created_at查找最后创建的记录(但在 db 中,它会四舍五入到秒,因此其中一些可能会以相同的时间结束)。或者你可以传入一个 uniq 属性并使用find_by作为该属性。 -
谢谢。做 Note.order(created_at: :desc).last.id 不一致(我假设你描述的原因)。如果无法访问刚刚创建的记录,我不知道如何进行 find_by。
-
当您在测试中调用
post时,您不知道参数中会包含什么吗?说{ body: "special body" },然后说find_by(body: "special body")。 -
恕我直言,是时候退后一步,考虑一下您的测试可能不正确 :) 无论如何,您不应该依赖增量 ID 来验证结果。更好的测试是检查你正在写的笔记的内容,看看它是否出现在笔记页面上。话虽如此,如果您绝对必须,您可以按
created_at时间戳对笔记进行排序,获取 ID 并从那里获取..
标签: ruby-on-rails ruby activerecord minitest