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

Ruby on rails Capybara:测试页面创建对象的当前路径,ruby-on-rails,rspec,capybara,Ruby On Rails,Rspec,Capybara,创建新对象后,应重定向到动作显示。如何检查当前路径 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_pe

创建新对象后,应重定向到动作显示。如何检查当前路径

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

对于迷失的路径,我需要id,但我如何创建id?或者如何更好地检查水豚的路径

由于创建的记录是数据库中最新的记录,因此可以使用MyActiveRecordModel.last

lost_pet = LostPet.last
expect(current_path).to eq lost_pet_path(lost_pet)
不使用水豚的等待行为-这意味着,由于点击是异步的(不等待屏幕上的任何东西,也不等待提交完成),您的测试可能非常脆弱。你最好使用

expect(page).to have_current_path(expected_path)
因为这将在检查预期路径时使用水豚的等待行为

除此之外,还存在一个问题,即在单击执行(异步)之后还没有创建lostSet对象,因此调用lostSet.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)) 
或者,将regex选项与have_current_path一起使用,不用担心验证url的实际id

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

或者类似的东西

我添加了lost_pet=LostPet.last和get error:Failure/error:expect(当前路径)。为eq lost_pet_path(lost_pet)ActionController::UrlGenerationError:No route matches{:action=>“show”,:controller=>“lost_pets”,:id=>nil}缺少必需的键:[:id]click_on的异步特性意味着此时很可能不会创建LostSet(如果使用除rack test之外的任何驱动程序),因此LostSet.last将为零——请参阅我的答案
expect(page).to have_current_path(/lost_pet\/[0-9]+/) # match the regex to whatever your urls actually are