Commit a4aac378

mo khan <mo@mokhan.ca>
2014-07-20 14:48:35
add create action to tutorials controller.
1 parent 969cae5
Changed files (4)
app
config
spec
app/controllers/api/v1/tutorials_controller.rb
@@ -6,6 +6,16 @@ module Api
       def index
         respond_with(@tutorials = current_user.tutorials)
       end
+
+      def create
+        respond_with(@tutorial = current_user.tutorials.create!(tutorial_params))
+      end
+
+      private
+
+      def tutorial_params
+        params.require(:tutorial).permit(:url, :image_url, :heading, :description)
+      end
     end
   end
 end
app/models/tutorial.rb
@@ -1,5 +1,5 @@
 class Tutorial < ActiveRecord::Base
-  validates :url,  :presence => true
+  validates :url, presence: true
   belongs_to :user
   acts_as_taggable
 
config/routes.rb
@@ -50,7 +50,7 @@ Cake::Application.routes.draw do
         resources :photos, only: [:index, :show, :create]
       end
       resources :categories, only: [:index]
-      resources :tutorials, only: [:index]
+      resources :tutorials, only: [:index, :create]
       resources :logins, :only => [:create]
     end
   end
spec/controllers/api/v1/tutorials_controller_spec.rb
@@ -0,0 +1,38 @@
+require "rails_helper"
+
+describe Api::V1::TutorialsController do
+  let(:user) { create(:user) }
+
+  before :each do
+    request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Token.encode_credentials(user.authentication_token)
+  end
+
+  describe "#index" do
+    let(:my_tutorial)  { create(:tutorial, user: user) }
+    let(:other_tutorial)  { create(:tutorial) }
+
+
+    it "returns the users tutorials" do
+      get :index, format: :json
+      expect(assigns(:tutorials)).to include(my_tutorial)
+      expect(assigns(:tutorials)).to_not include(other_tutorial)
+    end
+  end
+
+  describe "#create" do
+    it "creates a new tutorial" do
+      attributes = {
+        url: "https://twitter.com/",
+        image_url: "https://abs.twimg.com/a/1405611403/img/t1/front_page/exp_wc2014_gen_laurenlemon.jpg",
+        heading: "Twitter",
+        description: "Connect with your friends - and other fascinating people. Get in-the-moment updates on the things that interest you. And watch events unfold, in real time, from every angle.",
+      }
+      post :create, tutorial: attributes, format: :json
+
+      expect(assigns(:tutorial)).to be_present
+      expect(assigns(:tutorial).url).to eql(attributes[:url])
+      expect(assigns(:tutorial).description).to eql(attributes[:description])
+      expect(assigns(:tutorial).heading).to eql(attributes[:heading])
+    end
+  end
+end