RSpec-Rails (基礎篇)(4): 撰寫view測試

RSpec-Rails教學(基礎篇)全部內容

建立view測試檔案

$ mkdir spec/views
$ mkdir spec/views/posts
$ touch spec/views/posts/index_spec.rb

spec/views/posts/index_spec.rb

require 'rails_helper'

RSpec.describe "posts/index.html.erb", type: :view do
    it 'can render' do
        @post = Post.create(:title => "Big Title", :content => "content")
        @posts = Array.new(2, @post)
        render
        expect(rendered).to include("Title")
        expect(rendered).to include("Big Title")
    end
end

RSpec.describe "posts/index.json.jbuilder", type: :view do
    it "contains data" do
        @post = Post.create(:title => "Big Title", :content => "content")
        @posts = Array.new(2, @post)
        render
        expect(rendered).to include("id")   
        expect(rendered).to include("title")    
        expect(rendered).to include("content")
        expect(rendered).to include("Big Title")
    end
end


RSpec.describe "posts/index.pdf.prawn", type: :view do
    it "contains data" do
        @post = Post.create(:title => "Big Title", :content => "content")
        @posts = Array.new(2, @post)
        content = PDF::Inspector::Text.analyze(render).strings.join(",")
        expect(content).to include("Hello World")
        expect(content).to include("Big Title")
    end
end

建立edit頁面測試

$ touch spec/views/posts/edit_spec.rb

/spec/views/posts/edit_spec.rb

require 'rails_helper'

RSpec.describe "posts/edit.html.erb", type: :view do
    before(:each) do
        @post = Post.create(:title => "Big Title", :content => "content")
    end

    it "render partial" do
        render
        expect(response).to render_template(partial: "_form")
    end

    it "has link" do
        render
        expect(rendered).to include("Show")
        expect(rendered).to include("Back")     
    end
end

建立show頁面測試

$ touch spec/views/posts/show_spec.rb

將部分邏輯判斷整理到helper當中

/app/helpers/post_helpers.rb

module PostsHelper
    def render_content
        if not @post.content.nil?
            @post.content
        else
            content_tag(:p, "No Content")
        end
    end
end

將helper method填回show頁面的content當中。

/app/views/posts/show.html.erb

<%= render_content %>

撰寫show測試

/spec/views/posts/show_spec.rb

require 'rails_helper'

RSpec.describe "posts/show.html.erb", type: :view do
    it "renders 'No Content' when @post has no content" do
        @post = Post.create(:title => "Big Title", :content => nil)
        render
        expect(rendered).to include("No Content")
    end

    it "renders content when @post has content" do
        allow(view).to receive(:render_content).and_return("Stub Content")
        @post = Post.create(:title => "Big Title", :content => "I love rails")
        render
        expect(rendered).not_to include("No Content")
        expect(rendered).not_to include("I love rails")
        expect(rendered).to include("Stub Content")
    end
end