如何编写断言检查Controller方法呈现特定视图?

时间:2015-03-03 20:09:44

标签: ruby-on-rails ruby unit-testing ruby-on-rails-4

我正在使用Ruby 2.1.1运行Rails 4.

我在控制器中 def home render :index end 我正在编写一个Unit :: Test来检查控制器是否使用方法index呈现视图home

我该怎么写断言?到目前为止我有 test "home should have index" do assert true end

当然,我的测试通过,因为我有assert true,但是在查看文档并进行修改后,我仍然不确定如何为Controller编写适当的功能测试。许多来源不完整或含糊不清,看到Stack Overflow上出现了关于使用Unit :: Test编写简单功能测试的简单Stack Overflow问题,我认为这将是一个很好的问题。

我想要的只是一个明确的答案,断言我的功能测试检查home方法呈现index。一旦我弄清楚如何编写基本的功能测试,我想我将能够继续测试我的应用程序的其余部分。

干杯

TL; DR我不知道如何编写基本的功能测试。我怎么做?请单位::测试初学者友好。

2 个答案:

答案 0 :(得分:0)

使用assert_template断言请求是使用适当的模板文件或部分文件呈现的。

test "home should have index" do
  get :home
  assert_template 'index'
end

答案 1 :(得分:0)

添加到infused的答案:

  1. 这被视为特定控制器的功能测试,其功能和限制在RailsGuide here中有所描述。

  2. 如果你的控制器名称是StaticPagesController,那么测试应该在文件中:

    test/controllers/static_pages_controller_test.rb

  3. RailsGuide描述了如何测试渲染视图here

  4. 您可以像这样运行测试:

    $ bundle exec rake test

    或:

    $ bundle exec rake test:functionals

  5.   

    看看没有关于写一个简单的Stack Overflow问题   使用Unit :: Test的简单功能测试出现在Stack Overflow

    那是因为Rails有自己的测试框架。文件test/controllers/static_pages_controller_test.rb实际上如下所示:

    require 'test_helper'
    
    class StaticPagesControllerTest < ActionController::TestCase
    
      test 'home should get index' do
        get :home
        assert_template :index
      end
    
    end
    

    注意超类:ActionController::TestCase。作为RailsGuide notesActionController::TestCase包含MiniTest,Test::Unitmostly a drop in replacement