简体   繁体   中英

Test “dynamic” page title in a view spec (Rails 4 + RSpec 3)

I am currently following a tutorial but Rails and Rspec have evolved, especially for writing tests.

My goal is to test that when I visit the page " http://domain.fr /users/1 " the page title follow the format : "#{base_title} | #{@user.name}" where base_title is constant.

Before, I saw it was possible to use render_views in controller specs but it is not the best way and it does not exist anymore in Rails 4/RSpec 3.

My last try is :

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

I use an helper for rendering in application.html.erb : <title><%= title %></title>

Here is the helper :

def title
  base_title = "Simple App du Tutoriel Ruby on Rails"
  @title.nil? ? base_title : "#{base_title} | #{@title}"
end

And the show method from users_controller.rb :

def show
  @user = User.find(params[:id])
  @title = @user.name
end

I also added resources :users to my routes.rb file.

The above test fail because only the constant part of the title is rendered. Thus, I think Users#show is not called and @title not defined but I don't see how to achieve this.

Also my goal is to avoid calling assign() for each variable in my view as it can become problematic when you have a lot of variables to render.

Thanks for your help :)

You forgot to assign the title :

assign(:user, user)
assign(:title, user.name)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM