簡體   English   中英

Capybara:測試頁面創建對象的當前路徑

[英]Capybara: Test current path to page created object

創建新對象后應重定向到動作節目。 我如何檢查當前路徑?

feature 'add lost pet' do
  given(:data) {attributes_for(:lost_pet)}

  background do
    visit  root_path
    click_on 'Register new lost pet'
  end

  scenario 'add new lost pet with valid data' do
    within '#new_lost_pet' do
      fill_in 'Name', with: data[:name]
      fill_in 'Type', with: data[:type]
      fill_in 'Breed', with: data[:breed]
      fill_in 'Gender', with: data[:gender]
      fill_in 'Size', with: data[:size]
      fill_in 'Colour', with: data[:colour]
      fill_in 'Age', with: data[:age]
      fill_in 'Age unit', with: data[:age_unit]
      fill_in 'Description', with: data[:description]
      fill_in 'Collar description', with: data[:collar_description]
      check 'Desexed', :checked
      check 'Microchipped', :checked
      fill_in 'Microchip number', with: data[:microchipped_number]
      select '2015', from: "lost_pet[date_missing(1i)]"
      select 'October', from: 'lost_pet[date_missing(2i)]'
      select '10', from: 'lost_pet[date_missing(3i)]'
      fill_in 'Rewald', with: data[:rewald]
      fill_in 'Image', with: data[:image]
      fill_in 'Adress lost', with: data[:adress_lost]

      click_on 'Create'
    end  

    expect(current_path).to eq lost_pet_path(????)


  end

對於lost_pet_path我需要id,但是我如何創建id? 或者如何更好地檢查Capybara的路徑?

expect(current_path).to eq ...

不使用Capybara的等待行為 - 這意味着由於click_on是異步的(不等待屏幕上的任何內容,或者提交完成),您的測試可能非常不穩定。 你用得好多了

expect(page).to have_current_path(expected_path)

因為那將在檢查預期路徑時使用Capybara的等待行為。

最重要的是你有一個問題,就是在click_on執行(異步)之后還沒有創建LostPet對象,因此調用LostPet.last很可能會返回nil。 你有幾個選擇

等待頁面上出現的一些文本

expect(page).to have_text('Lost Pet created') # shows in a flash message, or header on the show page, etc
# since you know the show page is visible now you can query for the last LostPet created
expect(page).to have_current_path(lost_pet_path(LostPet.last)) 

或者,使用帶有have_current_path的正則表達式選項,並且不必擔心驗證URL的實際ID

expect(page).to have_current_path(/lost_pet\/[0-9]+/) # match the regex to whatever your urls actually are

或類似的東西

由於創建的記錄是數據庫中最新的記錄,因此可以使用MyActiveRecordModel.last

lost_pet = LostPet.last
expect(current_path).to eq lost_pet_path(lost_pet)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM