I have this code in a create
method inside a Rails controller:
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
To test this code, I have this expectation in an RSpec file:
expect(response).to redirect_to(assigns(:product))
Using assigns
is deprecated/has been moved to a gem and frankly I don't care if @product
or @my_product
has been created in the controller. Actually I just want to know if I have been redirected to /products/<some-id>
. Is there a (recommended) way to do so?
If you want render new you you'll need add gem 'rails-controller-testing'
to your Gemfile.
After read your comments i guess your action #create is look like that:
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: @product }
else
format.html { render :new }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
You could do a test like that:
describe 'POST /products' do
context 'when everithing is ok' do
it 'returns the product' do
post products_url, params: { product: { description: 'lorem ipsum', title: 'lorem ipsum' } }
expect(response).to redirect_to(product_url(Product.last))
end
end
context 'when something worong' do
it 'redirect to new' do
post products_url, params: { product: { description: 'lorem ipsum' } }
expect(response).to render_template(:new)
end
end
end