0

根据我对 AAA - 安排行为断言的理解,重要的是要明确什么代码用于安排、执行和断言。

在测试一个复杂的场景时,我习惯于在每次测试中多次执行相同的操作。排列发生变化,断言也发生变化。但是动作还是一样的。

最近我遇到了这段代码:

before do
    post 'somewhere'
end

it 'creates something' do
    expect 'something'.to be true
end

而且我不确定这是否是一个好习惯。例如,当我们添加上下文时,安排代码处于动作和断言的中间。

before do
    post 'somewhere'
end

[ some tests ]

context 'when a more complex scenario applies' do
    before do 
      [more complex arrangements]
    end

    it 'creates something more complex' do
        expect 'something'.to be true
    end
end

干这些动作是一个好习惯吗?

4

1 回答 1

0

是的。这仍然是可取的(恕我直言),因为如果您更改站点,那么您可以在一个地方更改所有测试的代码。只需制作一个帮助文件并在此处添加您的方法。

# spec/helpers.rb
module Helpers

  def method1(*args)
    # do something
  end

end

您可以通过 rails_helper 或在单个文件中添加它:

require 'helpers'
RSpec.configure do |config|
  config.include Helpers
end

然后你就像任何常规方法一样在你的规范中调用它们。

于 2021-02-20T14:28:05.977 回答