gpt4 book ai didi

ruby-on-rails - rails 中的辅助方法问题

转载 作者:太空宇宙 更新时间:2023-11-03 16:09:16 25 4
gpt4 key购买 nike

我有以下辅助方法 (app/helpers/application_helper.rb):

module ApplicationHelper

#Return a title on a per-page basis
def title
base_title = "Ruby on Rails Tutorial Sample App"
if @title.nil?
base_title
else
"#{base_title} | #{@title}"
end
end
end

这是 erb (app/views/layouts/application.html.erb):

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<%= csrf_meta_tag %>
</head>
<body>
<%= yield %>
</body>
</html>

我运行了一个 rspec 测试来查看这个辅助方法是否有效,但它似乎找不到标题。

这是错误信息:

Failures:

1) PagesController GET 'home' should be successful
Failure/Error: get 'home'
ActionView::Template::Error:
undefined local variable or method `title' for #<#<Class:0x991ecb4>:0x991315c>
# ./app/views/layouts/application.html.erb:4:in `_app_views_layouts_application_html_erb__248109341_80250010__979063050'
# ./spec/controllers/pages_controller_spec.rb:8:in `block (3 levels) in <top (required)>'

2) PagesController GET 'home' should have the right title
Failure/Error: get 'home'
ActionView::Template::Error:
undefined local variable or method `title' for #<#<Class:0x991ecb4>:0x9d7d094>
# ./app/views/layouts/application.html.erb:4:in `_app_views_layouts_application_html_erb__248109341_82566280__979063050'
# ./spec/controllers/pages_controller_spec.rb:13:in `block (3 levels) in <top (required)>'

谁能告诉我我做错了什么?

更新:

我通过执行以下操作包含了帮助程序:

 describe PagesController do
include ApplicationHelper
render_views

describe "GET 'home'" do
it "should be successful" do
get 'home'
response.should be_success
end

it "should have the right title" do
get 'home'
response.should have_selector("title",
:content => "Ruby on Rails Tutorial Sample App | Home")
end
end


//and some more

但是我仍然遇到同样的错误

最佳答案

在您看来,默认情况下不包括助手。

您可以 mock out the helper methods using the template object :

template.should_receive(:title).and_return("Title")

然后您可以测试您的 helpers分别。

或者,您可以通过简单地执行以下操作将您的助手包含在您的 View 规范中:

include ApplicationHelper

编辑

describe PagesController do
include ApplicationHelper

describe "GET 'home'" do
it "should be successful" do
controller.template.should_receive(:title).and_return("Title")
get 'home'
response.should be_success
end
end
end

关于ruby-on-rails - rails 中的辅助方法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7165586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com