I am trying to test my #new view in a controller
class ApplicationController < ActionController::Base
before_action :current_cart
protect_from_forgery with: :exception
private
def current_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
@cart
end
end
class controller < ApplicationController
def new
if @cart.line_items.empty?
redirect_to store_url, :notice => "Your cart is empty"
return
end
@order = Order.new
respond_to do |format|
format.html
format.xml { render :xml => @order }
end
end
Spec:
describe "GET #new" do
it "renders the :new template" do
product = FactoryGirl.create(:product)
@cart.add_product(product.id)
get :new
response.should render_template :new
end
end
@cart
is not defined??
Any clues, thank you
You don't need to check or add to @cart in the test. You aren't testing the saving of the cart, you are testing whether or not your new would render. If you took that out it would pass. Also it's preferred not to rescue exceptions like that. You can do a @cart ||= Cart.find_or_create_by_id(session[:cart_id])
method instead
Edit: I missed that redirect.
describe "GET #new" do
let(:cart) { FactoryGirl.create(:cart) }
let(:product) { FactoryGirl.create(:product) }
it "renders the :new template" do
cart.add_product(product.id)
session[:cart_id] = cart.id
get :new
response.should render_template :new
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.