Commit 4438229

mo khan <mo@mokhan.ca>
2016-05-01 20:36:32
implement Gyms#create.
1 parent e5ab9ef
Changed files (3)
app
config
spec
app/controllers/gyms_controller.rb
@@ -7,4 +7,23 @@ class GymsController < ApplicationController
     @gym = Gym.new
     @gym.build_location
   end
+
+  def create
+    @gym = Gym.new(secure_params)
+    if @gym.save
+      redirect_to gyms_path
+    else
+      flash[:error] = @gym.errors.full_messages
+      render :new
+    end
+  end
+
+  private
+
+  def secure_params
+    params.require(:gym).permit(
+      :name,
+      location_attributes: [:address, :city, :region, :country, :postal_code]
+    )
+  end
 end
config/routes.rb
@@ -10,7 +10,7 @@ Rails.application.routes.draw do
   end
   resources :programs, only: [:show]
   resources :profiles, only: [:new, :create, :show, :edit, :update], constraints: { id: /[^\/]+/ }
-  resources :gyms, only: [:index, :new]
+  resources :gyms, only: [:index, :new, :create]
   get "/u/:id" => "profiles#show", constraints: { id: /[^\/]+/ }
   get "/dashboard" => "training_sessions#index", as: :dashboard
   get "/terms" => "static_pages#terms"
spec/controllers/gyms_controller_spec.rb
@@ -27,4 +27,52 @@ describe GymsController do
       expect(assigns(:gym).location).to be_present
     end
   end
+
+  describe "#create" do
+    context "valid params" do
+      before :each do
+        post :create, gym: {
+          name: 'SAIT',
+          location_attributes: {
+            address: '1301 16 Ave NW',
+            city: 'Calgary',
+            region: 'AB',
+            country: 'CA',
+            postal_code: 'T2M 0L4',
+          }
+        }
+      end
+
+      it 'redirects to the listing page' do
+        expect(response).to redirect_to(gyms_path)
+      end
+
+      it 'creates a new gym' do
+        expect(Gym.count).to eql(1)
+        gym = Gym.last
+        expect(gym.name).to eql('SAIT')
+        expect(gym.location).to be_present
+        expect(gym.location.address).to eql('1301 16 Ave NW')
+        expect(gym.location.city).to eql('Calgary')
+        expect(gym.location.region).to eql('AB')
+        expect(gym.location.country).to eql('CA')
+        expect(gym.location.postal_code).to eql('T2M 0L4')
+      end
+    end
+
+    context "invalid params" do
+      before :each do
+        post :create, gym: { name: '' }
+      end
+
+      it 'displays an error' do
+        expect(flash[:error]).to eql(assigns(:gym).errors.full_messages)
+      end
+
+      it 'renders the form with the original values entered' do
+        expect(response).to render_template(:new)
+        expect(assigns(:gym)).to be_present
+      end
+    end
+  end
 end