require 'spec_helper'

describe "Network Test", :js => true, :type => :feature, :capybara_feature => true, :slow => true do

  subject { page }

  let(:user) { FactoryGirl.create(:user) }

  describe "native client" do

    before(:each) do
      LatencyTester.delete_all
      emulate_client
      sign_in_poltergeist user
    end

    it "success" do

      # verify last_jam fields get updated too

      user.last_jam_updated_at.should be_nil
      user.last_jam_updated_reason.should be_nil
      user.last_jam_addr.should be_nil
      user.last_jam_locidispid.should be_nil

      FactoryGirl.create(:latency_tester)

      open_user_dropdown
      page.find('.test-network').trigger(:click)
      find('h1', text: 'Test Router & Network')

      # start the test
      find('.start-network-test').trigger(:click)
      find('.user-btn', text: 'RUN NETWORK TEST ANYWAY').trigger(:click)
      find('.network-test-score-audio .scored-clients', text: '5')
      find('.network-test-score-video .scored-clients', text: '2')

      wait_for_ajax # waiting for Diagnostic post to finish

      sleep 1  # even after AJAX is done, because we are in a different connection, we have to give time to fully commit data

      user.reload
      user.last_jam_updated_at.should_not be_nil
      user.last_jam_updated_reason.should == User::JAM_REASON_NETWORK_TEST
      user.last_jam_addr.should == ip_address_to_int('127.0.0.1')
      user.last_jam_locidispid.should == locidispid_from_ip('127.0.0.1')
    end
  end

  describe "normal browser" do
    before(:each) do
      sign_in_poltergeist user
    end

    it "not available in regular browser" do
      open_user_dropdown
      page.should_not have_selector('.test-network')
    end
  end
end
