Update device create API

- Update the existing device if a device with existing unique_id is
   present
This commit is contained in:
Yedhu Krishnan
2015-10-18 11:13:20 +05:30
parent fb3b514f3d
commit 3947889282
3 changed files with 29 additions and 6 deletions

View File

@@ -1,9 +1,15 @@
class DevicesController < ApplicationController class DevicesController < ApplicationController
skip_before_filter :verify_authenticity_token
respond_to :json respond_to :json
def create def create
device = Device.create(device_params) device = Device.find_or_initialize_by(unique_id: device_params[:unique_id])
respond_with device, status: :created device.assign_attributes(device_params)
if device.save
render json: { access_token: device.access_token }, status: :created
else
render json: { error: device.errors.full_messages }, status: :unprocessable_entity
end
end end
private private

View File

@@ -4,10 +4,27 @@ RSpec.describe DevicesController, type: :controller do
describe "POST #create" do describe "POST #create" do
it "creates a device" do it "creates a device" do
expect { expect do
post :create, device: attributes_for(:device), format: :json post :create, device: attributes_for(:device), format: :json
}.to change{ Device.count }.by(1) end.to change{ Device.count }.by(1)
#expect(response).to have_http_status(:success) end
describe "when device with existing unique id comes" do
before(:example) do
device = create(:device)
@device_params = { model: "New Device", unique_id: device.unique_id }
end
it "does not create a new device" do
expect do
post :create, device: @device_params, format: :json
end.to change { Device.count }.by(0)
end
it "updated the existing device with new params" do
post :create, device: @device_params, format: :json
expect(Device.last.model).to eq("New Device")
end
end end
end end

View File

@@ -7,7 +7,7 @@ RSpec.describe Device, type: :model do
it { should validate_presence_of :model } it { should validate_presence_of :model }
it { should validate_uniqueness_of :unique_id } it { should validate_uniqueness_of :unique_id }
describe "after create" do describe "before create" do
it "generates an access token for the device" do it "generates an access token for the device" do
expect(device.access_token).not_to be_nil expect(device.access_token).not_to be_nil
end end