【问题标题】:Capybara Rspec Rails get ID for pathCapybara Rspec Rails 获取路径 ID
【发布时间】:2016-05-06 13:38:52
【问题描述】:

使用 capybara/rspec 来测试 rails。想要使用 id 检查当前路径是否正确生成,但无法访问创建的联系人 id。

示例期望: 本地主机:3000/contacts/27

收到的示例: 本地主机:3000/联系人/

代码库:

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

有什么想法/想法吗?

【问题讨论】:

  • 变量@contact.id在哪里定义?
  • hi @Зелёный 在 contacts_controller.rb 中。
  • 为什么您认为可以在功能测试中从控制器访问实例变量 (@contact)?你不能。
  • 我认为它可以访问。是否可以访问数据库以检索 URL 的 ID?或者这是不可能的?其次,您将如何测试创建的 URL 是否正确?
  • 你试过Contact.last.id吗?

标签: ruby-on-rails rspec path capybara


【解决方案1】:

您无法从功能测试中访问控制器实例变量。但是,您可以访问数据库,并且由于您在此测试中首先或最后只创建了一个联系人,因此应该可以工作 -

expect(page).to have_current_path(contact_path("#{Contact.last.id}"))

话虽如此,当您的测试只是检查是否可以查看现有联系人时,注册用户并通过 UI 创建联系人并没有多大意义,因为您可以只为您的功能创建数据库记录测试。您可能想研究一下 FactoryGirl 的方法来构建您的功能测试对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多