gpt4 book ai didi

ruby-on-rails - 在验收规范中测试或不测试什么?

转载 作者:行者123 更新时间:2023-12-04 04:40:07 26 4
gpt4 key购买 nike

使用 Rspec/Capybara 进行 RSpec 测试。

假设我们有带有基本 CRUD 的 PostsController。
要测试什么?
创建新帖子(#new),显示所有帖子(#index),销毁帖子(#destroy)等,如下面的代码,或以其他方式:It allows user to create new post; when posts doesnt't exist it renders 404 ...; when user is blocked render 403 ?

require 'spec_helper'

feature 'Post management', js: true do
background { login_user }
given!(:project) { create(:project) }

scenario 'creating new post' do
expect do
visit new_project_post_path(project)
fill_in 'post_title', with: 'Hello, I am the Doctor'
fill_in 'post_text', with: 'Trust me.'
click_button 'Add post'
end.to change(Post, :count).by(1)
end

given!(:project) { create(:project_with_posts) }

scenario 'listing posts' do
visit project_posts_path(project)
project.posts.each do |post|
page.should have_content post.title
end
end

given!(:post) { create(:post) }

scenario 'showing posts' do
visit project_post_path(post.project, post)
page.should have_content post.title
page.should have_content post.text
end
end

最佳答案

这只能是一个固执的答案,但这里是我关于验收测试的经验法则:

测试用户期望的行为

这是,正如您提到的“验收”测试:堆栈持有者希望为功能提供通常的行为,不要担心如果某些内容无效或用户忘记登录会发生什么( Controller 规范已经测试过)。

测试用户应该看到什么

这不是检查数据库是否处于正确状态的地方。测试 Flash 消息以及页面中可能发生的视觉变化(某个项目是否不再出现在列表中)。

例如,在您的“创建新帖子”场景中,您可以测试:

within '#flash_message' do
page.should have_content 'Post created'
end

within '#posts' do
page.should have_content "My new post"
end

你可以写更多的细节,但它会与单元测试重复,这会更快(如果你可以检查 Post received call to #create stub ,为什么要检查 Post.count 是否为 +1 ?)。在您的页面上测试一些文本或元素就足以说明各个部分可以很好地协同工作。

测试实际用户行为

没有用户“访问待办事项列表项编辑页面”。他们从主页开始,然后转到待办事项列表,然后单击特定项目行上的“编辑”。

在您的代码中,您可以替换:
visit project_posts_path(project)

与:
def visit_posts
visit '/'

within '#projects' do
first( 'a.posts' ).click
end

end

scenario 'listing posts' do
visit_posts
project.posts.each do |post|
page.should have_content post.title
end
end

这运行时间更长,但无论如何,在存在一两年后,您的验收测试套件将太长而无法运行,无法等待,您将把它放在持续集成服务器上。这里重要的是测试一切都按预期工作,而不是特定的行为。没有比从主页(或实际用户会直接打开的任何页面,例如管理主页)开始更好的方法来做到这一点。

关于ruby-on-rails - 在验收规范中测试或不测试什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19007072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com