Ruby on Rails 3 + Rspec + Capybara: check response status

匿名 (未验证) 提交于 2019-12-03 08:52:47

问题:

I migrated from Webrat to Capybara and now i get a lot of errors. For example in webrat i could use that in integration test:

response.should be_success

But Capybara shows that:

Failure/Error: response.should be_success      NoMethodError:        undefined method `success?' for nil:NilClass

Is there any method that provides such function?

UPD: My spec:

require 'spec_helper'  describe "Admins" do   before(:each) do     @admin = FactoryGirl.create(:admin)      visit '/'     click_link "Login"     fill_in "Email",  :with => @admin.email     fill_in "Password", :with => 'qwerty'     click_button "Sign in"   end    describe "Admin panel" do     it "should have correct links" do       click_link "User"       response.should be_success     end   end end

回答1:

You're mixing controller and request specs.

In a controller spec you check the response, in a request spec, you check the page content, since you have only access to the html.



回答2:

I can't find any indication of shortcuts like a success? method, but if your driver supports it, you can do something like this:

visit(some_path) page.status_code.should == 200

This was added a while back, but doesn't seem to be well-documented. Additionally, some drivers simply don't give the information to capybara. Selenium was mentioned in particular - it'll crash if you try this while using the Selenium driver.



回答3:

This may help you:

expect(page).to have_http_status(200)


回答4:

Please make use of asset_exists? function in next gist

def asset_exists?(src)   js_script = <<JSS   xhr = new XMLHttpRequest();   xhr.open('GET', '#{src}', true);   xhr.send();   JSS    page.execute_script(js_script)   status = page.evaluate_script('xhr.status') # get js variable value   status == 200 || status == 302 end

https://gist.github.com/yovasx2/1c767114f2e003474a546c89ab4f90db for more details



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!