Commit 465ab6a

mo khan <mo@mokhan.ca>
2016-12-31 19:28:54
add api endpoint to create a new workout.
1 parent eeeb135
Changed files (4)
app
controllers
views
config
spec
app/controllers/api/workouts_controller.rb
@@ -6,4 +6,27 @@ class Api::WorkoutsController < Api::Controller
   def new
     @workout = current_user.next_workout_for(current_user.next_routine)
   end
+
+  def create
+    workout = current_user.workouts.build(secure_params)
+    workout.occurred_at = DateTime.now
+    workout.save!
+    render nothing: true, status: :created
+  end
+
+  private
+
+  def secure_params
+    params.require(:workout).permit(
+      :routine_id,
+      :body_weight,
+      exercise_sets_attributes: [
+        :exercise_id,
+        :target_duration,
+        :target_repetitions,
+        :target_weight,
+        :type,
+      ]
+    )
+  end
 end
app/views/api/workouts/_workout.json.jbuilder
@@ -6,6 +6,6 @@ json.exercises workout.sets.includes(:exercise).order(:created_at).group_by(&:ex
   json.id exercise.id
   json.name exercise.name
   json.sets sets.sort_by(&:created_at) do |set|
-    json.partial! 'sets/set', set: set
+    json.partial! 'api/sets/set', set: set
   end
 end
config/routes.rb
@@ -17,6 +17,6 @@ Rails.application.routes.draw do
 
   namespace :api, defaults: { format: 'json' }  do
     resources :sessions, only: [:create]
-    resources :workouts, only: [:index, :new]
+    resources :workouts, only: [:index, :new, :create]
   end
 end
spec/controllers/api/workouts_controller_spec.rb
@@ -63,4 +63,32 @@ describe Api::WorkoutsController do
       ])
     end
   end
+
+  describe "#create" do
+    include_context "stronglifts_program"
+    let(:body_weight) { rand(250.0).lbs }
+
+    it "creates the workout with the selected exercises" do
+      post :create, params: {
+        workout: {
+          routine_id: routine_b.id,
+          body_weight: body_weight,
+          exercise_sets_attributes: [{
+            exercise_id: squat.id,
+            target_repetitions: 5,
+            target_weight: 200,
+            type: "WorkSet",
+          }]
+        }
+      }, format: :json
+
+      expect(response).to have_http_status(:created)
+      expect(user.reload.workouts.count).to eql(1)
+      expect(user.last_routine).to eql(routine_b)
+      workout = user.workouts.last
+      expect(workout.body_weight).to eql(body_weight)
+      expect(workout.routine).to eql(routine_b)
+      expect(workout.sets.count).to eql(1)
+    end
+  end
 end