如何为仅呈现html的控制器方法编写rspec测试?

时间:2018-06-08 01:14:40

标签: ruby-on-rails rspec controller

我的routes.rb:

Rails.application.routes.draw do
  root 'application#hello'
end

我的application_controller.rb:

class ApplicationController < ActionController::Base
  def hello
    render html: "Hello, world!"
  end
end

我已经尝试过这个规范,但它不起作用:

RSpec.describe ApplicationController do
  render_views

  describe '#hello' do
    it 'renders hello world' do
      get :hello_world

      expect(response.body).to include("Hello, world!")
    end
  end
end

我收到此错误:

Failures:

  1) ApplicationController#hello renders hello world
     Failure/Error: get :hello_world

     ActionController::UrlGenerationError:
       No route matches {:action=>"hello_world", :controller=>"application"}

如何编写Rspec测试来测试此方法是否呈现此html?

1 个答案:

答案 0 :(得分:1)

错误在于它无法找到路线hello_world,请尝试更改

it 'renders hello world' do
  get :hello_world

  expect(response.body).to include('hello world')
end

it 'renders hello world' do
  get :hello

  expect(response.body).to include('hello world')
end

并查看是否有帮助