我正在編寫使用RoR生成的PDF的規格&大蝦。這些PDF有很多過濾器選項(其中24個)。爲了不錯過任何重要的規格,我在before :context
塊中生成過濾器選項並將它們保存在實例變量中。在共享示例調用中使用let循環變量
當我的問題開始時,試圖迭代所有篩選器選項並運行共享示例,以測試不同的篩選器沒有太大改變的基礎知識。
這是我的代碼看起來像所有這些過濾器和單證篩選器(filter_setting
方法只是一個輔助訪問特定@major_filter_options
):
describe 'pdf' do
before :context do
@major_filter_options = {}
@major_filter_options.define_them
end
describe 'basic content' do
before :context do
@filter_options_with_docu = {}
# find all the filters that have the docu option enabled
@major_filter_options.each do |key, mfo|
@filter_options_with_docu[key] = mfo if key.to_s.include? 'docu'
end
end
24.times do |t| # can't access major_filter_options.size here.. it's nil.
include_examples 'first_3_pages' do
let(:pdf) do
filter_options = filter_setting(@major_filter_options.keys[t])
ProjectReport::ReportGenerator.new.generate(project, filter_options, user).render
end
let(:page_analysis) { PDF::Inspector::Page.analyze(pdf) }
end
end
12.times do |t| # @print_options_with_docu is also nil at this point
include_examples 'documentation_content' do
let(:pdf) do
filter_options = filter_setting(@filter_options_with_docu.keys[t])
ProjectReport::ReportGenerator.new.generate(project, filter_options, user).render
end
let(:page_analysis) { PDF::Inspector::Page.analyze(pdf) }
end
end
# ...
end
我有2個大問題:
一個是,這24.times
,12.times
等(有一堆他們)打擾我,因爲它使維護困難得多。一個新的過濾器選項會改變所有的值,並且在我看來,找到所有的值來改變它們是非常容易出錯的。
的另一個問題是,變量重述這樣的: 12.times do |t|
實際上並不似乎遍歷時,我的這些let
的內部:
let(:pdf) do
filter_options = filter_setting(@major_filter_options.keys[t])
puts t
# ...
end
的puts t
這裏每次打印11次(每次過濾器也一樣)。 經過一番閱讀,我發現a gist example。這個問題看起來很相似,但可惜的是,在它周圍的區塊沒有做太多的工作。
24.times do |t|
describe
# same as before
end
end
有趣的是,雖然,在設置的老毛病又犯puts t
時,這將是6每一次,它給我留下了一點困惑。
我還應該提一下,將它們分開的原因是我已經共享了僅適用於某些過濾器的示例。如果有人有更好的想法,例如迭代@major_filter_options
,然後根據當前散列號key
調用特定的共享示例,那麼我就是耳朵!
我不能肯定地說,但'include_examples'每個上下文只有一次的作品。我認爲你必須用一個uniq環境來包圍它,比如'context「...#{t}」do' – slowjack2k