require 'test_helper'
require 'net/http'
require File.dirname(__FILE__) + '/../lib/hoptoad_notifier/lib/hoptoad_notifier'

class Net::HTTP < Net::Protocol
  mattr_accessor :test_unit_class

  def connect
  end

  def post path, body, headers
    self.class.test_unit_class.post path, body, headers
  end
end

class ApplicationController < ActionController::Base
  include HoptoadNotifier::Catcher
  module ::HoptoadNotifier::Catcher
    def public_environment?
      true
    end
  end
end

class PostingFromHoptoadNotifierTest < ActionController::IntegrationTest
  context "with a connection from the plugin to the application" do
    setup do
      post '/accounts', {
        :account => {
          :name => 'testaccount',
          :subdomain => 'testaccount',
          :admin_user_attributes => {
            :name => 'test user',
            :email => 'test@example.org',
            :password => 'password',
            :password_confirmation => 'password'
          }
        }
      }

      host! 'testaccount.test.host'
      post '/projects', {
        :project => {
          :name => 'project'
        }
      }


      @project = Project.last
      assert_redirected_to "/projects/#{@project.id}/groups"

      Net::HTTP::test_unit_class = self
      host! 'test.host'
    end

    should "deny access with an incorrect api key" do
      HoptoadNotifier.configure do |config|
        config.api_key = 'punch to the face!'
      end

      assert_no_difference 'Notice.count' do
        HoptoadNotifier.notify RuntimeError.new
        assert_response :unprocessable_entity
      end
    end

    context "with a valid API key" do
      setup do
        HoptoadNotifier.configure do |config|
          config.api_key = @project.api_key
        end
      end

      should "create a notice" do
        assert_difference 'Notice.count' do
          HoptoadNotifier.notify RuntimeError.new
        end
      end

      should "put a new notice into the correct project" do
        assert_difference '@project.notices.count' do
          HoptoadNotifier.notify RuntimeError.new
          assert_response :created
        end
      end
    end
  end
end

