我是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
请告知如何做好。
答案 0 :(得分:3)
假设测试将产品记录插入到您的数据库中,也许您可以
product = Product.last
然后才进行断言
expect(page.current_path).to eq(product_path(product)) # or product.id
或者使用have_current_path
代替eq
,正如Tom Walpole在评论中所说的那样。