简体   繁体   中英

Stub Rails UJS/Ajax responses status to test returning message in Rspec/Capybara feature test

I have AJAX calls initiated by Rails UJS that I would like to test. specifically, I have used Rails UJS ajax events to provide for cases of errors.

I would like to test them but I don't know how to tell rspec/capybara to "stub" and assume the error code

$("button").
      on('ajax:error',function(event,xhr, status, error){
          if(status == "timeout") {
            var msg;
            msg = Messenger().post({
              message:    "This is taking too long"
            });          
          } else {
            var msg;
            msg = Messenger().post({
              message:    "it seems there is a bug. Please try again."
            });
          };
        });

I would like to do something like the following:

describe "test returning error message", js: true do
   it "should be successful" do        
        visit deal_page_path(deal)
        first('a.button').click 
        stub(:xhr.status) = "timeout"           
        expect(page).to have_content('This is taking too long') 
      end
end

How to do this?

Note: the ajax requests are internal they don't go to third party API or services (such as facebook for ex).

When testing with Capybara (JS enabled drivers) it has no access to the request or response except through the changes it creates in the browser. You could build a test mode into your relevant controllers that could be turned on and off to allow it to output the errors you want, but the cleanest way to do this is probably to use a programmable proxy like puffing-billy which will allow you to selectively return whatever you'd like for any given request from the browser. One thing to realize is that this isn't testing that app correctly returns errors, it's just testing that your front-end handles errors the way you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM