У меня был такой же вопрос некоторое время назад, и кто-то указал мне на Extended Backus-Naur Form .
Это имеет смысл, потому что программирование может быть использовано для создания потенциально безграничных результатов. Документация не может отображать пример для каждого возможного случая. Хорошим примером совместного использования я вам помогу, но как только вы сможете прочитать базовый синтаксис, который вы можете создать свой собственный код.
Я не уверен, является ли это столь же каноническая / лучшая практика как [1 131] ответ @El'Magnifico использование RSpec::Mocks.with_temporary_scope
, но я нашел, что при помощи around
рычаг вместо before
, смог динамично ввести before
блоки (и подобный) в эти example_group
, приведя к ним работающий вместе с моим тестом:
# spec/spec_helper.rb
RSpec.configure do |config|
# ..snip..
config.include RequestForgerySpecHelper, type: :feature
# ..snip..
end
# spec/support/request_forgery_spec_helper.rb
module RequestForgerySpecHelper
def self.included(base)
base.around(:all) do |ex|
puts "around all start"
ex.example_group.prepend_before do
puts "around all inside prepend_before"
end
ex.example_group.append_after do
puts "around all inside append_after"
end
ex.run
puts "around all end"
end
end
end
Теперь, если мы принимаем, наш тест уже печатает некоторые журналы before
, after
, и в test
сам, наш вывод похож на это:
around all start
around all inside prepend_before
inside spec file before
inside spec file test
inside spec file after
around all inside append_after
around all end
, поскольку мы теперь динамично вводим наш before
рычаг в тот же контекст как наши тесты, мы больше не видим следующей ошибки:
before
не доступно из примера (например,it
блок) или от конструкций, которые работают в пределах примера (например,before
,let
, и т.д.). Это только доступно на группе в качестве примера (например,describe
илиcontext
блок)
ex
параметр, предоставленный эти around
, рычаг является экземпляром [1 134] RSpec::Core::Example::Procsy
, который предоставляет доступ к RSpec::Core::Example
экземпляр через example
атрибут.
RSpec::Core::Example
предоставляет нам доступ к эти RSpec::Core::ExampleGroup
связанный с этим тестом через example_group
метод.
RSpec::Core::ExampleGroup
предоставляет нам доступ к DSL/methods разрешение нам динамично определить before
/ after
/ let
/ и т.д. блоки, не инициировав not available from within an example
ошибка; как мы видим путем списка методов в, любопытствуйте:
ls RSpec::Core::ExampleGroup
# RSpec::Core::Hooks#methods: after append_after append_before around before hooks prepend_after prepend_before
# RSpec::Core::MemoizedHelpers::ClassMethods#methods: let let! subject subject!
# RSpec::Core::ExampleGroup.methods:
# add_example currently_executing_a_context_hook? define_nested_shared_group_method describe ensure_example_groups_are_configured fcontext ffeature fit fspecify include_examples location parent_groups run scenario specify superclass_metadata update_inherited_metadata xexample xspecify
# before_context_ivars declaration_locations delegate_to_metadata described_class example fdescribe file_path focus id it metadata pending run_after_context_hooks set_it_up store_before_context_ivars top_level? with_replaced_metadata xfeature
# children define_example_group_method descendant_filtered_examples description example_group feature filtered_examples for_filtered_examples idempotently_define_singleton_method it_behaves_like next_runnable_index_for remove_example run_before_context_hooks set_ivars subclass top_level_description xcontext xit
# context define_example_method descendants each_instance_variable_for_example examples fexample find_and_eval_shared fscenario include_context it_should_behave_like ordering_strategy reset_memoized run_examples skip superclass_before_context_ivars traverse_tree_until xdescribe xscenario