在视图规范中测试 "dynamic" 页面标题 (Rails 4 + RSpec 3)
Test "dynamic" page title in a view spec (Rails 4 + RSpec 3)
我目前正在学习教程,但 Rails 和 Rspec 已经有所改进,尤其是在编写测试方面。
我的目标是测试当我访问页面“http://domain.fr/users/1”时页面标题遵循以下格式:"#{base_title} | #{@user.name}"
其中 base_title 是常量。
之前,我看到可以在控制器规格中使用 render_views,但这不是最好的方法,并且在 Rails 4/RSpec 3 中不再存在。
我最后一次尝试是:
require 'rails_helper'
describe "users/show.html.erb", type: :view do
it "Should finally render a correct title" do
user = FactoryGirl.create(:user)
assign(:user, user)
render template: "users/show.html.erb", layout: "layouts/application.html.erb"
expect(rendered).to have_selector("title", text: user.name)
end
end
我在 application.html.erb 中使用辅助渲染:<title><%= title %></title>
帮手来了:
def title
base_title = "Simple App du Tutoriel Ruby on Rails"
@title.nil? ? base_title : "#{base_title} | #{@title}"
end
以及 show 方法 users_controller.rb :
def show
@user = User.find(params[:id])
@title = @user.name
end
我还将 resources :users
添加到我的 routes.rb 文件中。
上面的测试失败了,因为只渲染了标题的常量部分。因此,我认为未调用 Users#show 并且未定义 @title 但我不知道如何实现此目的。
此外,我的目标是避免为我视图中的每个变量调用 assign(),因为当您有很多变量要渲染时,它可能会出现问题。
感谢您的帮助:)
您忘记分配 title
:
assign(:user, user)
assign(:title, user.name)
我目前正在学习教程,但 Rails 和 Rspec 已经有所改进,尤其是在编写测试方面。
我的目标是测试当我访问页面“http://domain.fr/users/1”时页面标题遵循以下格式:"#{base_title} | #{@user.name}"
其中 base_title 是常量。
之前,我看到可以在控制器规格中使用 render_views,但这不是最好的方法,并且在 Rails 4/RSpec 3 中不再存在。
我最后一次尝试是:
require 'rails_helper'
describe "users/show.html.erb", type: :view do
it "Should finally render a correct title" do
user = FactoryGirl.create(:user)
assign(:user, user)
render template: "users/show.html.erb", layout: "layouts/application.html.erb"
expect(rendered).to have_selector("title", text: user.name)
end
end
我在 application.html.erb 中使用辅助渲染:<title><%= title %></title>
帮手来了:
def title
base_title = "Simple App du Tutoriel Ruby on Rails"
@title.nil? ? base_title : "#{base_title} | #{@title}"
end
以及 show 方法 users_controller.rb :
def show
@user = User.find(params[:id])
@title = @user.name
end
我还将 resources :users
添加到我的 routes.rb 文件中。
上面的测试失败了,因为只渲染了标题的常量部分。因此,我认为未调用 Users#show 并且未定义 @title 但我不知道如何实现此目的。
此外,我的目标是避免为我视图中的每个变量调用 assign(),因为当您有很多变量要渲染时,它可能会出现问题。
感谢您的帮助:)
您忘记分配 title
:
assign(:user, user)
assign(:title, user.name)