require 'test_helper'

class API::V1::ThingsControllerTest < ActionDispatch::IntegrationTest

  test 'should not grant access without authorisation' do
    get '/api/v1/things', headers: @request_header
    assert_response :unauthorized
    post '/api/v1/things', headers: @request_header
    assert_response :unauthorized
    get '/api/v1/things/1', headers: @request_header
    assert_response :unauthorized
    patch '/api/v1/things/1', headers: @request_header
    assert_response :unauthorized
    put '/api/v1/things/1', headers: @request_header
    assert_response :unauthorized
    delete '/api/v1/things/1', headers: @request_header
  end

  test 'user should get all things' do
    things = [FactoryGirl.create(:thing),
                 FactoryGirl.create(:thing)]
    get '/api/v1/things', headers: @user_request_header
    assert_response :ok
    assert_content data: [{type: 'things', attributes: {name: things[0].name, icon: things[0].icon}},
                          {type: 'things', attributes: {name: things[1].name, icon: things[1].icon}}]
  end

  test 'admin should get all things' do
    things = [FactoryGirl.create(:thing),
                 FactoryGirl.create(:thing)]
    get '/api/v1/things', headers: @admin_request_header
    assert_response :ok
    assert_content data: [{type: 'things', attributes: {name: things[0].name, icon: things[0].icon}},
                          {type: 'things', attributes: {name: things[1].name, icon: things[1].icon}}]
  end

  test 'admin should be able to create a new thing' do
    thing = test_thing
    post '/api/v1/things', params: thing, as: :json, headers: @admin_request_header
    assert_response :created
    persistent_thing = Thing.find_by_name thing[:data][:attributes][:name]
    assert_content data: {type: 'things', attributes: {name: persistent_thing.name, icon: persistent_thing.icon}}
  end

  test 'user should not be able to create a new thing' do
    post '/api/v1/things', params: test_thing, as: :json, headers: @user_request_header
    assert_response :forbidden
  end

  private

  def test_thing()
    {data: {
        type: 'things',
        attributes: {
            name: FFaker::Lorem.word,
            icon: FFaker::Lorem.word
        }
    }}
  end

end


