Skip to content

Instantly share code, notes, and snippets.

@davidrhyswhite
Created March 30, 2013 10:11
Show Gist options
  • Save davidrhyswhite/5276200 to your computer and use it in GitHub Desktop.
Save davidrhyswhite/5276200 to your computer and use it in GitHub Desktop.
class Api::UsersController < ApplicationController
def index
@users = User.all
render json: @users
end
def show
@user = User.find params[:id]
render json: @user
end
def create
@user = User.new user_params
if @user.save
render json: @user, status: :created, location: api_user_url(@user)
else
render json: @user.errors, status: :unprocessable_entity
end
end
def update
@user = User.find params[:id]
if @user.update user_params
head :no_content
else
render json: @user.errors, status: :unprocessable_entity
end
end
def destroy
@user = User.find params[:id]
@user.destroy
head :no_content
end
end
require 'spec_helper'
describe Api::UsersController do
render_views
let(:user) { |build :user, id: 1 }
context "index action should return 'OK'" do
before do
@users = (1..3).map { |n| build :user, id: n }
User.expects(:all).returns(@users).once
get :index
end
it { should assign_to(:users).with(@users) }
it { should respond_with(:ok) }
end
context "show action should return 'OK'" do
before do
User.expects(:find).returns(user)
get :show, id: user
end
it { should assign_to(:user).with(user) }
it { should respond_with(:ok) }
end
context "create action is invalid" do
before do
User.any_instance.expects(:valid?).returns(false)
User.any_instance.expects(:errors)
post :create, user: attributes_for(:invalid_user)
end
it { should respond_with(:unprocessable_entity) }
end
context "create action is valid" do
before do
User.any_instance.expects(:valid?).returns(true)
post :create, user: attributes_for(:user)
end
it { should assign_to(:user).with(user) }
it { should respond_with(:created) }
end
context "update action is invalid" do
before do
User.expects(:find).returns(user)
User.any_instance.expects(:valid?).returns(false)
User.any_instance.expects(:errors)
put :update, id: user, user: attributes_for(:invalid_user)
end
it { should respond_with(:unprocessable_entity) }
end
context "update action is valid" do
before do
User.expects(:find).returns(user)
User.any_instance.expects(:valid?).returns(true)
put :update, id: user, user: attributes_for(:user)
end
it { should respond_with(:no_content) }
end
context "destroy action" do
before do
User.expects(:find).returns(user)
User.any_instance.expects(:destroy)
delete :destroy, id: user
end
it { should respond_with(:no_content) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment