Ruby 在 Rails 上使用 Rspec 功能测试,获取您在测试时创建的对象的 ID
Ruby on Rails using Rspec feature test, get id of object you create while the tests
我是 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
请指教如何做对。
假设测试将产品记录插入到您的数据库中,也许您可以这样做
product = Product.last
然后才做出断言
expect(page.current_path).to eq(product_path(product)) # or product.id
或使用 have_current_path
代替 Tom Walpole 在评论中建议的 eq
。
我是 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
请指教如何做对。
假设测试将产品记录插入到您的数据库中,也许您可以这样做
product = Product.last
然后才做出断言
expect(page.current_path).to eq(product_path(product)) # or product.id
或使用 have_current_path
代替 Tom Walpole 在评论中建议的 eq
。