diff --git a/app/controllers/devices_controller.rb b/app/controllers/devices_controller.rb index 3a47030..2a11f5d 100644 --- a/app/controllers/devices_controller.rb +++ b/app/controllers/devices_controller.rb @@ -1,9 +1,15 @@ class DevicesController < ApplicationController + skip_before_filter :verify_authenticity_token respond_to :json def create - device = Device.create(device_params) - respond_with device, status: :created + device = Device.find_or_initialize_by(unique_id: device_params[:unique_id]) + 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 private diff --git a/spec/controllers/devices_controller_spec.rb b/spec/controllers/devices_controller_spec.rb index a71fef6..a1dd3b5 100644 --- a/spec/controllers/devices_controller_spec.rb +++ b/spec/controllers/devices_controller_spec.rb @@ -4,10 +4,27 @@ RSpec.describe DevicesController, type: :controller do describe "POST #create" do it "creates a device" do - expect { + expect do post :create, device: attributes_for(:device), format: :json - }.to change{ Device.count }.by(1) - #expect(response).to have_http_status(:success) + end.to change{ Device.count }.by(1) + 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 diff --git a/spec/models/device_spec.rb b/spec/models/device_spec.rb index 0ac9995..a063287 100644 --- a/spec/models/device_spec.rb +++ b/spec/models/device_spec.rb @@ -7,7 +7,7 @@ RSpec.describe Device, type: :model do it { should validate_presence_of :model } it { should validate_uniqueness_of :unique_id } - describe "after create" do + describe "before create" do it "generates an access token for the device" do expect(device.access_token).not_to be_nil end