【问题标题】:Ruby on Rails using Rspec feature test, get id of object you create while the testsRuby on Rails 使用 Rspec 功能测试,获取您在测试时创建的对象的 ID
【发布时间】:2016-02-20 21:58:44
【问题描述】:

我是 Ruby On Rails 的新手,想知道在测试期间获取对象 id(在我的例子中是产品 id)的最佳做法是什么。

我在功能测试中通过在字段中填写数据(不是以编程方式)创建了一个产品,并且该产品已成功创建。 如何获取其他测试的产品 ID?

例如,现在我需要 @product_id 来提供以下测试:

expect(page.current_path).to eq(product_path)

我收到下一个错误,因为我无法提供 @product_id:

 Failure/Error: expect(page.current_path).to eq(product_path)
 ActionController::UrlGenerationError:
   No route matches {:action=>"show", :controller=>"products"} missing required keys: [:id]

我的测试:

    require 'rails_helper'

RSpec.feature 'Creating Products' do

  before do
    @user_test = User.create(email: 'test@test.com', password: 'password')
    @product_test_name = 'Test product'
    @product_test_price = '20'
  end

  scenario 'User creates a new product' do
    login_as(@seller_test)
    visit '/'
    have_link 'New Product'
    visit new_product_path

    fill_in 'Name', with: @product_test_name
    fill_in 'Price', with: @product_test_price

    click_button 'Create Product'

    expect(page).to have_content('Product has been created')

    expect(page).to have_content(@product_test_name)
    expect(page).to have_content(@product_test_description)
    expect(page).to have_content(@product_test_price)

    expect(page.current_path).to eq(product_path)
  end
  end



请指教如何正确操作。

【问题讨论】:

  • 不要做expect(page.current_path).to eq(product_path) - 而是做expect(page).to have_current_path(product_path) - 它不能解决你的问题(@dhacke 的答案是这样做的)但它会在未来让你头疼跨度>

标签: ruby-on-rails rspec capybara bdd specifications


【解决方案1】:

假设 test 将产品记录插入到您的数据库中,也许您可​​以这样做

product = Product.last

然后才做出断言

expect(page.current_path).to eq(product_path(product)) # or product.id

或者使用 have_current_path 代替 eq,正如 Tom Walpole 在 cmets 中建议的那样。

【讨论】:

  • 感谢@dhacke 的回复,非常有帮助。
    product = Product.last
    对我来说效果很好。在代码的第二行我做了一个小改动:
    expect(page.current_path).to eq(product_path(product))
    谢谢大家的帮助!
  • 哦,对 product_path 的电话很好,我会更新我的答案。
  • @dhacke 更喜欢 have_current_path 匹配器而不是 eq - 它具有水豚等待行为,因此它会在必要时等待当前路径更改 - 使测试不那么脆弱
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多