Rails控制器(集成?)测试出现问题



我正在制作我的第一个Rails应用程序,所以这可能是基本的。

在我的用户配置文件中,我想让用户添加标题和描述。我使它们成为User模型的属性,并将其添加到routes.rb:中

resources :users do
member do
post 'update_description'
end
end

相同的方法(尚未编写)将处理这两个属性。为了练习TDD,我想写一个测试,简单地显示,如果用户提交了一个标题,那么控制器就会将其保存到数据库中。我原以为这将是一个集成测试,但我没能找到正确的方法。(这应该是一个集成测试吗?)但是,经过研究,我设法在相关的控制器测试文件中编写了一个有效的post语句。这是控制器测试:

test "profile submits new title and description successfully" do
log_in_as(@user)
get :show, id: @user
assert_nil @user.title
post :update_description, id: @user, params: { title: "Lorem ipsum" }
# Next:
# @admin.reload.title
# assert @admin.title == "Lorem ipsum"
# assert_template 'users/show'
# Etc.
end

这会引发以下错误:

ERROR["test_profile_submits_new_title_and_description_successfully", UsersControllerTest, 2017-10-22 21:42:52 -0400]
test_profile_submits_new_title_and_description_successfully#UsersControllerTest (1508722972.17s)
ActionView::MissingTemplate:         ActionView::MissingTemplate: Missing template users/update_description, application/update_description with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
* "/var/lib/gems/2.3.0/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates"
* "/home/globewalldesk/startthis/app/views"
* "/var/lib/gems/2.3.0/gems/web-console-2.0.0.beta3/app/views"
test/controllers/users_controller_test.rb:83:in `block in <class:UsersControllerTest>'
test/controllers/users_controller_test.rb:83:in `block in <class:UsersControllerTest>'

我想这意味着Rails正在寻找一个视图文件,但找不到,但我不明白post :update_description为什么要找视图。。。我以为它会在没有视图的情况下发布信息(我有一条类似的路线,在没有视图时也一样)。update_description方法在Users控制器中。我做了很多研究,但我不知道我做错了什么。帮助TIA。

编写测试的方式看起来像是集成测试。但我个人建议写一个系统测试。因为我看到您创建update_description成员路由只是为了更新User对象?这是不必要的-您的User资源已经有了editupdate操作,所以您可以删除该成员路由。

集成测试用于检查工作流以及如何与应用程序的不同部分交互。虽然系统检查是针对用户交互的,但基本上是检查用户在浏览器中会做和看到的事情。此外,在我看来,用这种技术编写测试要简单得多(至少在这个级别上)。

所以你的系统测试看起来像:

setup do
log_in_as(@user) // or what ever code to visit login page and login user
end
test "profile submits new title successfully" do
visit edit_user_path
fill_in "Title", with: "Lorem ipsum"
click_on "Save"
assert_response :redirect
follow_redirect!
assert_select "Title", text: "Lorem ipsum"
end

这假设用户提交表单后,应用程序重定向到user_path(@user)(显示页面)。

集成测试看起来像:

test "profile submits new title successfully" do
log_in_as(@user) // or what ever code to login user
get "/user/#{@user.id}/edit"
assert_response :success
updated_title = "Lorem ipsum"
patch :update, user: { id: @user.id, title: updated_title }
assert_response :redirect
follow_redirect!
assert_response :success
assert_select "Title", text: "Lorem ipsum"
end

注意-我还没有测试过这个,我使用了Capybara和其他工具,但没有Minitest。但在这个简单的过程中,我认为这应该奏效。

如果你还没有这样做,请查看文档。。

最新更新