2

我正在使用 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在终端窗口中运行命令行时的输出。

这是正确的测试方法吗?


相关问题:

4

1 回答 1

0

你的问题会征求一些意见,但我会尝试用一些例子来证明我的观点。

简短回答:不,这不是您应该编写 RSpec(或任何测试)描述的方式。这是非常规的,不会为额外的代码增加太多价值。

长答案:RSpec 是一个 BDD(行为驱动开发)工具,旨在帮助描述代码的行为和意图,同时编写自动化测试。当您考虑代码的行为时,将预期结果添加到测试描述中真的会增加很多价值吗?如果是这样,也许您应该重新考虑您正在测试的内容。

例如,假设您有一个 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

VS

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

在第一个测试中,描述中的预期结果真正给你带来了什么?它是否告诉您有关用户预期行为的任何信息?并不真地。

Take your example. If I was coming along to your project and saw a test description like that, I would be confused because it doesn't really tell me what is being tested. I would still need to look at the code to understand what is going on. Compare these two examples:

it "displays the #{expected_page_title} page title" do
  view.content_for(:page_title).should have_content(expected_page_title)
end

Which would give you something in the console like:

"displays the My Awesome Title page title"

Compare that to:

it "should translate the page title" do
  view.content_for(:page_title).should have_content(expected_page_title)
end

Which would be exactly the same in the console as it is in the test:

"should translate the page title"

Your obviously free to choose whichever one you want, but I am speaking from a few years of testing experience and highly recommend you don't do this.

于 2012-04-07T16:12:47.687 回答