加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Capybara:测试页面创建对象的当前路径

发布时间:2020-12-17 01:51:50 所属栏目:百科 来源:网络整理
导读:创建新对象后应重定向到动作节目.我如何检查当前路径? 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
创建新对象后应重定向到动作节目.我如何检查当前路径?

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

或类似的东西

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读