What's the meaning of page and page.body in Capybara

3.2k views Asked by At

I'm a newbie try to test my Rails project using Capybara, but I'm confused with the meaning of page and page.body, when I try to detect some string from my div: (in :js=>true mode)

<div>"some content"</div>

Some of my test will pass with

page.should have_content "some content"

Some will pass with

page.body.should have_content "some content"

I try to puts the content but only "page.body" will give me some valuable information, the "page" itself will show me nothing, and I can't find any solid explanation about what page and page.body did. Can anyone help me?

2

There are 2 answers

0
Thomas Walpole On BEST ANSWER

page is the current Capybara session - calling #find/#first/#visit/etc is the same as calling page.find(...), page.first(...), etc.

page.body returns the html source of the page.

Most of the time you would not want to be calling matchers on page.body, so 99.9% of the time you should be using

page.should have_content(...) 

or the equivalent expect syntax. This is because calling matchers on page.body actually runs the returned string through a parser and queries against that, rather than querying in the browser you're testing in.

2
steve klein On

I believe this syntax is deprecated and you should change to:

expect(page).to have_content "some content"

This will check the rendered page for the content you specify. If you are unsure of whether you are rendering the page you expect and want to debug your test, you can use puts page.body to do so.

You can learn more about should and expect here.