Code Review: Rspec Tests

I am writing a rails application for my mom to enter her bakery orders for her business. The Order page has a form to search or add a new customer, so i can streamline the process as much as possible. In the Order create method, I either get a customer array or a customer ID.

Here's the order create method in the controller:

RUBY:
  1. def create
  2.    
  3.     new_customer = params[:order][:customer_id].blank? ? true : false
  4.    
  5.     if new_customer
  6.       @customer = Customer.create(params[:customer])
  7.       if @customer.valid?
  8.         @customer.orders.create(params[:order])       
  9.         flash[:notice] = 'New customer was added and order was created successfully'
  10.         redirect_to orders_url
  11.       else
  12.         flash[:notice] = 'Please fill in all required fields'
  13.         render :action => 'new'
  14.       end
  15.     else
  16.       @customer = Customer.find params[:order][:customer_id]
  17.       @customer.orders.create(params[:order])
  18.       flash[:notice] = 'Order was successfully created.'
  19.       redirect_to orders_url
  20.     end
  21.  
  22.  end

Ok? anybody see a better way to do that? It took me awhile to figure out the right branching. Now for my rspec tests. This can take two paths -- new customer or existing customer.

Test for New Customer:

RUBY:
  1. describe OrdersController, "handling POST /orders with a new customer" do
  2.  
  3.   before do
  4.     @order = mock_model(Order, :to_param => "1")
  5.    
  6.     Order.stub!(:create).and_return(@order)
  7.    
  8.     @params = {:customer_id => nil}
  9.    
  10.     @customer = mock_model(Customer, :to_param => "1")
  11.     @customer.stub!(:orders).and_return(Order)
  12.     Customer.stub!(:create).and_return(@customer)
  13.   end
  14.  
  15.   def post_with_successful_save
  16.     @customer.should_receive(:valid?).and_return(true)
  17.     post :create, :order => @params
  18.   end
  19.  
  20.   def post_with_failed_save
  21.     @customer.should_receive(:valid?).and_return(false)
  22.     post :create, :order => @params
  23.   end
  24.  
  25.   it "should create a new customer" do
  26.     Customer.should_receive(:create).with(anything()).and_return(@customer)   
  27.     post_with_successful_save
  28.   end
  29.  
  30.   it "should create a new order" do
  31.     Order.should_receive(:create).with(anything()).and_return(@order) 
  32.     post_with_successful_save
  33.   end
  34.  
  35.   it "should redirect to the new order on successful save" do
  36.     post_with_successful_save
  37.     response.should redirect_to(orders_url)
  38.   end
  39.  
  40.   it "should re-render 'new' on failed save" do
  41.     post_with_failed_save
  42.     response.should render_template('new')
  43.   end
  44. end

Hows that look? do I catch all the cases for the New Customer scenario?

Leave a Comment