require File.expand_path('../../spec_helper', __FILE__)

describe CustomFieldsController, logged: :admin do

  let(:issue_custom_field) { FactoryGirl.create(:issue_custom_field, :easy_group_id => nil) }

  render_views

  context 'update form' do
    it 'edit' do
      post :update_form, :id => issue_custom_field.id, :custom_field => {:name => 'test name'}, :format => 'js'
      expect(response).to be_success
      expect(response.body).to include('test name')
    end

    it 'new' do
      post :update_form, :type => 'IssueCustomField', :custom_field => {:name => 'test name'}, :format => 'js'
      expect(response).to be_success
      expect(response.body).to include('test name')
    end
  end

  context 'groups' do
    let(:easy_group) { FactoryGirl.create(:easy_custom_field_group) }

    it 'new group on create' do
      put :create, :type => 'IssueCustomField', :custom_field => {:name => 'test name', :easy_group_id => 'New group', :field_format => 'string'}
      expect(EasyCustomFieldGroup.find_by(:name => 'New group')).not_to eq(nil)
    end

    it 'assign group on create' do
      easy_group
      expect {
        put :create, :type => 'IssueCustomField', :custom_field => {:name => 'test name', :easy_group_id => easy_group.id.to_s, :field_format => 'string'}
      }.to change(EasyCustomFieldGroup, :count).by(0)
      expect(CustomField.where(:easy_group_id => easy_group.id).count).to eq(1)
    end

    it 'new group on update' do
      post :update, :id => issue_custom_field, :custom_field => {:easy_group_id => 'New group'}
      group = EasyCustomFieldGroup.find_by(:name => 'New group')
      expect(group).not_to eq(nil)
      expect(issue_custom_field.reload.easy_group_id).to eq(group.id)
    end

    it 'assign group on update' do
      easy_group
      expect {
        post :update, :id => issue_custom_field, :custom_field => {:easy_group_id => easy_group.id.to_s}
      }.to change(EasyCustomFieldGroup, :count).by(0)
      expect(CustomField.where(:easy_group_id => easy_group.id).count).to eq(1)
      expect(issue_custom_field.reload.easy_group_id).to eq(easy_group.id)
    end
  end

end
