登录 主页

rails controller unit test

2023-10-08 09:21AM

在 Rails 中,你可以使用单元测试(unit test)来测试控制器(controller)。测试控制器各动作需要编写功能测试(functional test)

控制器负责处理应用收到的请求,然后使用视图渲染响应。功能测试用于检查动作对请求的处理,以及得到的结果或响应(某些情况下是 HTML 视图)。

一个简单的例子:

# test/controllers/posts_controller_test.rb

# 引入测试帮助器,它包含了一些测试所需的设置和辅助方法
require 'test_helper'

# 定义了一个名为 PostsControllerTest 的测试类,继承自 ActionController::TestCase

class PostsControllerTest < ActionController::TestCase

# 定义一个测试方法,它测试能否成功访问 index 动作
  test "should get index" do

    # 发送一个 GET 请求到 index 动作
    get :index

    # 断言响应的状态码为成功(HTTP 200)
    assert_response :success
  end

 # 定义一个测试方法,它测试能否成功创建一篇文章

  test "should create post" do

    # 断言在执行块中的代码后,Post.count 的值会增加
    assert_difference('Post.count') do

      # 发送一个 POST 请求到 create 动作,并传递参数 { post: { title: "New Post", body: "Lorem Ipsum" } }
      post :create, params: { post: { title: "New Post", body: "Lorem Ipsum" } }
    end

    # 断言重定向到新创建的文章页面

    assert_redirected_to post_path(assigns(:post))
  end

  # 其他测试...
end

然后可以在命令行里面使用下面的命令来运行这个单元测试

bundle exec rails test test/controllers/posts_controller_test.rb

然后会显示

Run options: --seed 62744

# Running:

.

Finished in 0.206153s, 4.8508 runs/s, 4.8508 assertions/s.

1 runs, 1 assertions, 0 failures, 0 errors, 0 skips

这样就算成功了

返回>>

登录

请登录后再发表评论。

评论列表:

目前还没有人发表评论