请求排查Ruby on Rails中Contact页面测试失败的代码错误
Let's break down why your test is failing and how to fix it quickly:
What's Going Wrong
Looking at your error message, two key issues stand out:
- Your test expects the page title to be
<Contact | Ruby on Rails Tutorial Sample App>, but the actual title returned is just<Ruby on Rails Tutorial Sample App> - The
Expected 0 to be >= 1error is a side effect—this means theassert_selectmethod couldn't find a title tag matching your expected text, so it counted 0 matches instead of the required minimum of 1.
The core problem is that your app's main layout file isn't using the page-specific title content you're providing in the Contact view.
Step-by-Step Fix
Open your application's main layout file at
app/views/layouts/application.html.erbLocate the
<title>tag section. Right now, it's likely hardcoded to something like:<title>Ruby on Rails Tutorial Sample App</title>Update the tag to include the yielded title from your view:
<title><%= yield(:title) %> | Ruby on Rails Tutorial Sample App</title>This line tells Rails to pull in the
'Contact'value you set withprovide(:title, 'Contact')in your view and append it to the base app title, creating the exact format your test expects.Re-run the failing test to confirm it passes:
rails test test/controllers/static_pages_controller_test.rb:26
Why This Works
You're correctly using provide(:title, 'Contact') in your Contact view to define a page-specific title segment, but your layout wasn't configured to display that segment. The yield(:title) call in the layout bridges this gap, inserting your view's custom title text into the final page title.
While you're at it, double-check that your Help and About views also use provide(:title) (which they should, based on your test code) and that the layout renders them correctly—this will keep those tests passing too.
内容的提问来源于stack exchange,提问作者iThompkins

