I want to write a View
test. What should I do?
Step 1. Learn the view template
<% content_for :head do %>
<title>Project Name</title>
<link
rel="preload"
as="image"
href="<%= vite_asset_url 'images/logo.jpg' %>"
/>
<% end %>
<% @blogs.each_with_index do |blog| %>
<li><%= blog.title %></li>
<% end %>
Here I see
- View variable
@blogs
- Rails helper
vite_asset_url
Step 2. How to stub
a rails helper?
To do that I'm going to use the following way. Here in view
I stub vite_asset_url
and it will return a string "vite_asset_url".
allow(view).to
receive(:vite_asset_url).and_return("vite_asset_url")
Step 3. How to stub
a view variable?
To do that I use assign
test helper.
assign(:blogs, [blog1, blog2, blog2])
Step 4. How a test should look?
It looks like that:
require 'rails_helper'
RSpec.describe "site/landing/index", type: :view do
let!(:published_blogs) do
create_list(:blog, 3, :published, :for_blog) do |blog, index|
blog.title = "Blog Title #{index.next}"
blog.save!
end
end
before do
allow(view).to
receive(:vite_asset_url).and_return("vite_asset_url")
end
it "renders attributes in show page" do
assign(:blogs, published_blogs)
render
expect(rendered).to match(/Blog Title 1/)
expect(rendered).to match(/Blog Title 2/)
expect(rendered).to match(/Blog Title 3/)
end
end
That is it!
Happy Coding!
Top comments (0)