[英]Using Rails 5 and minitest, how can I access a record that was created in the test?
在切換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
找到的“最后一個” Note.last.id
。
如何設置錨點:到record_that_was_just_created.id
?
這里的答案很晚,很高興您得到了所需的結果!
... 以防其他任何人閱讀此內容以尋找測試方法 ...
簡短的答案是-您應該始終知道測試中正在使用的數據...因為您可以進行測試。 最常見的3種方法...
在setup
方法中,您
@account = Accounts(:first)
(需要yaml文件中的匹配條目) @account = @user.account.build(field: value, field2: value)
因此,您對問題有字面上的答案-對不確定的數據進行測試是一種不好的做法Shaunak
也是這么說的。
以上可能就足夠了-但是您的面向細節的測試應該在單元測試中-在這里您不會針對db進行調用並使測試成為最慢的版本。 您的集成級別人員應該只測試創建是否成功-您已經知道其中的數據有效。
為了獲得最佳體驗,您可能希望對上述3種setup
方法中的某些方法進行單元測試,並在測試中使用@account
,以便針對將要創建的驗證進行測試...
因此,單元測試將是...
setup
@account = @user.account.build # avoid hitting db unnecessarily versus create
@account.field = value
@account.field2 = value2
end
def test_details_pass_activerecord_validations
signin @user
@account.test_specific_fields = value # stuff not all the tests use
assert @account.valid? # trigger all the activerecord validations, but not db
end
從那里您的集成...
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
# Your setup method above should have most of the intialization
# ... basically @account = @user.account .note would be setup, but not inserted
signin @user
assert_difference('@user.account.notes.count') do
post notes_url(@account), params: { note: { body: @account.note.body } }
end
assert_redirected_to notes_url(@account, anchor: @account.whatever_field)
end
我想通了。 顯然,有一種方法可以在測試中訪問控制器的實例變量,因此我通過將assert_redirected_to更改為來使其工作
assert_redirected_to notes_url(@user.account.hash_id, anchor: controller.instance_variable_get(:@note).id)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.