I am pretty new to Ruby On Rails and am wondering what is the best practice to get an object id (in my case it is a product id) that was created during the test.
I created a product in the feature test by filling in data in fields (not programmatically) and the product has been created successfully. How can I get the product id for other tests?
For example right now I need @product_id to provide to the following test:
expect(page.current_path).to eq(product_path)
I am getting the next Error because I can't provide @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]
My Test:
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
Please advice how to do it right.
Assuming that test inserts a product record into your database, perhaps you can do
product = Product.last
and only afterwards make the assertion
expect(page.current_path).to eq(product_path(product)) # or product.id
Or use have_current_path
in lieu of eq
as Tom Walpole suggests in the comments.