我有一个控制器从url slug获取product.id
并将其分配给@product
实例变量。
产品具有状态,如果不是for_sale,则访问" / product / product.id
"会将您重定向到root_url
class ProductController < ApplicationController
before_action :still_available, only: [:new, :create]
def show
@product = Product.find_by(id: params[:id])
end
private
def still_available
product = Product.find_by(id: params[:id])
unless product.for_sale?
redirect_to root_url
end
end
应用程序/规格/集成:
require 'rails_helper'
RSpec.describe 'product page', :type => :request do
it 'redirects to the home page if product sold' do
get "/product/2"
expect(response).to redirect_to(root_url)
end
end
应用程序/测试/装置/产品:
two:
id: 2
status: 2
(status: 2
映射到sold
)
错误:
Failures:
1) product page redirects to the home page if product sold
Failure/Error: get "/product/2"
NoMethodError:
undefined method `for_sale?' for nil:NilClass