我正在使用 Ruby on Rails 3.2.2 和 rspec-rails-2.8.1。我想输出有关将要运行的测试的更多信息,例如,以这种方式:
# file_name.html.erb
...
# General idea
expected_value = ...
it "... #{expected_value}" do
...
end
# Usage that I am trying to implement
expected_page_title =
I18n.translate(
'page_title_html'
:user => @user.firstname
)
it "displays the #{expected_page_title} page title" do
view.content_for(:page_title).should have_content(expected_page_title)
end
注意:“输出”是指当您运行 rspec 时输出的那些。 --format documentation
终端窗口中的命令行。
这是一种正确的测试方式吗?
相关问题:
最佳答案
你的问题将征求一些意见,但我会尝试用一些例子来证明我的观点。
简短回答:不,这不是您编写 RSpec(或任何测试)描述的方式。这是非常规的,不会为额外代码增加太多值(value)。
长答案:RSpec 是一种 BDD(行为驱动开发)工具,旨在帮助描述代码的行为和意图,同时编写自动化测试。当您考虑代码的行为时,将预期结果添加到测试描述中真的会增加很多值(value)吗?如果是这样,也许您应该重新考虑要测试的内容。
例如,假设您有一个 User 类,并且您想要测试一个连接用户名字和姓氏的方法:
describe User do
expected_full_name = 'Software Guy'
subject { User.new(first: 'Software', last: 'Guy') }
it 'should have the full name #{expected_full_name}' do
subject.full_name.should == 'Software Guy'
end
end
对比
describe User do
subject { User.new(first: 'Software', last: 'Guy') }
it 'should have a full name based on the first and last names' do
subject.full_name.should == 'Software Guy'
end
end
在第一个测试中,描述中的预期结果会给您带来什么?它是否告诉您有关用户的预期行为的任何信息?并不真地。
举个例子。如果我在参加您的项目时看到了这样的测试描述,我会感到困惑,因为它并没有真正告诉我正在测试什么。我仍然需要查看代码以了解发生了什么。比较这两个例子:
it "displays the #{expected_page_title} page title" do
view.content_for(:page_title).should have_content(expected_page_title)
end
这会在控制台中给你一些东西,比如:
“显示 My Awesome Title 页面标题”
比较一下:
it "should translate the page title" do
view.content_for(:page_title).should have_content(expected_page_title)
end
这在控制台中与在测试中完全相同:
“应该翻译页面标题”
显然你可以自由选择你想要的任何一个,但我是根据几年的测试经验说的,强烈建议你不要这样做。
关于ruby-on-rails - 这是输出有关将要运行的测试的更多信息的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10055219/