Mathieu
Mathieu

Reputation: 4787

Rspec/capybara - simulate switch from Online to offline within a test (webkit driver)

I have a ruby on Rails 4 app. A user loads a page (called deal_page) then he clicks on a button which loads a Rails UJS modal message.

If he is online WHEN he clicks the button, I show a message using javascript offline status recognition (inside the Rails UJS ajax event).

on('ajax:error',function(event,xhr, status, error){
            var isOnLine = navigator.onLine;
            event.preventDefault();
            if (isOnLine) {
              //do stuff }
            else {
              // for disconnected users WHEN triggering call to server, invite to reconnect           
              var msg;
              msg = Messenger().post({
                message:            "You lost internet,You need to be connected"
              });
            }

          });

I want to test in rspec/capybara (I use webkit driver) that the right content ("You need to be connected. Please connect and try again") is displayed in that case in my feature test.

context "As signed-in visitor who is OFFLINE line when he clicks on the area triggering the modal" do 

it "displays the right message " do
        visit deal_page_path(deal)
        # HOW TO ASSERT THAT THE USER LOSES HIS INTERNET CONNECTION
        # USER GOES OFFLINE 
        first("a#button").click            
        within('ul.messenger') do           
          expect(page).to have_content('You lost internet,You need to be connected')
        end
      end

  end

The complexity is that I can't disconnect him from the beginning of the test as he needs to be connected to load the page visit deal_page_path(deal) but then I want to simulate that he loses the internet connection.

How to achieve this ?

Upvotes: 1

Views: 551

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49910

Assuming you're just checking window.naviagtor.onLine to determine whether or not it is on/offline (not depending on any events or anything) and because you're using capybara-webkit (won't work in selenium since FF won't let you overwrite navigator, not sure about poltergeist) you can just overwrite window.navigator with the result you want to get. You'll also need to generate an error response for your ajax request, which you can do with puffing-billy

page.execute_script "window.navigator = { onLine: false }"

Upvotes: 1

Related Questions