[英]Capybara Rspec Rails get ID for path
使用capybara / rspec測試導軌。 想要檢查當前路徑是否正確生成了ID,但無法訪問創建的聯系人ID。
預期示例:localhost:3000 / contacts / 27
收到的示例:localhost:3000 / contacts /
代碼庫:
feature 'contacts' do
before do
visit '/'
click_link 'Sign up'
fill_in 'Email', with: 'test@test.com'
fill_in 'Password', with: '123456'
fill_in 'Password confirmation', with: '123456'
click_button 'Sign up'
click_link 'Add a contact'
fill_in 'Firstname', with: 'John'
fill_in 'Surname', with: 'Jones'
fill_in 'Email', with: 'test@test.com'
fill_in 'Phone', with: '223344'
attach_file('contact[image]', Rails.root + 'spec/mouse1.jpeg')
click_button 'Create Contact'
end
context 'view a contact' do
scenario 'click contact to view details' do
click_link('Mouse1')
expect(page).to have_content 'John Jones 223344 test@test.com'
expect(page).to have_xpath("//img[contains(@src, \/html/body/a[2]/img\)]")
expect(page).to have_current_path(contact_path("#{@contact.id}"))
end
end
驚訝的是插值沒有起作用,並使用以下方法為NilClass拋出錯誤未定義的方法'id'。 顯然,它無法訪問ID。
expect(page).to have_current_path(contact_path("#{@contact.id}"))
還嘗試將其替換為@p = Contact.find_by_id(params[:id])
然后在插值中傳入@p。 但是拋出錯誤undefined local variable or method params
有什么想法/想法嗎?
您不能從功能測試中訪問控制器實例變量。 不過,您可以訪問數據庫,並且由於您在此測試中僅創建了一個聯系人,所以第一個或最后一個應該可以正常工作-
expect(page).to have_current_path(contact_path("#{Contact.last.id}"))
話雖如此,當您只為功能測試創建數據庫記錄時,僅在測試僅檢查可以查看現有聯系人的情況下注冊用戶並通過UI創建聯系人並沒有多大意義。 您可能想研究一下FactoryGirl來構建功能測試對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.