类: RSpec::Core::Example

继承
Object
  • Object
显示所有
定义于
lib/rspec/core/example.rb

概述

注意

示例块是在 ExampleGroup 实例的上下文中评估的,而不是在 Example 实例的上下文中。

用于 ExampleGroup 子类的实例的包装器。RSpec::Core::Example 的实例由示例定义方法(例如 it)返回,并被传递给 itbeforeafteraroundletsubject 块。

这使我们能够提供有关每个单独示例的丰富元数据,而无需在 ExampleGroup 中直接添加大量方法,用户可能会无意中重新定义这些方法。

对于根据示例元数据的状态配置日志记录和/或采取某些操作非常有用。

示例


RSpec.configure do |config|
  config.before do |example|
    log example.description
  end
  config.after do |example|
    log example.description
  end
  config.around do |example|
    log example.description
    example.run
  end
end
shared_examples "auditable" do
  it "does something" do
    log "#{example.full_description}: #{auditable.inspect}"
    auditable.should do_something
  end
end

另请参见

定义在命名空间下

类: ExecutionResultProcsy

实例属性摘要 折叠

实例方法摘要 折叠

构造函数详细信息

#initialize(example_group_class, description, user_metadata, example_block = nil) ⇒Example

此方法是私有 API 的一部分。如果可能,您应该避免使用此方法,因为它可能会在将来被删除或更改。

创建一个新的 Example 实例。

参数

  • example_group_class (Class)

    声明此 Example 的 ExampleGroup 子类

  • description (String)

    传递给 it 方法(或别名)的字符串

  • user_metadata (Hash)

    传递给 it 的其他参数,用作元数据

  • example_block (Proc) (默认值: nil)

    表示示例的代码块

186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/rspec/core/example.rb', line 186
def initialize(example_group_class, description, , example_block=nil)
  @example_group_class = example_group_class
  @example_block       = example_block
  # Register the example with the group before creating the metadata hash.
  # This is necessary since creating the metadata hash triggers
  # `when_first_matching_example_defined` callbacks, in which users can
  # load RSpec support code which defines hooks. For that to work, the
  # examples and example groups must be registered at the time the
  # support code is called or be defined afterwards.
  # Begin defined beforehand but registered afterwards causes hooks to
  # not be applied where they should.
  example_group_class.examples << self
  @metadata = Metadata::ExampleHash.create(
    @example_group_class., ,
    example_group_class.method(:next_runnable_index_for),
    description, example_block
  )
  config = RSpec.configuration
  config.(@metadata)
  # This should perhaps be done in `Metadata::ExampleHash.create`,
  # but the logic there has no knowledge of `RSpec.world` and we
  # want to keep it that way. It's easier to just assign it here.
  @metadata[:last_run_status] = config.last_run_statuses[id]
  @example_group_instance = @exception = nil
  @clock = RSpec::Core::Time
  @reporter = RSpec::Core::NullReporter
end

实例属性详细信息

#exceptionvoid (只读)

返回在此示例运行的上下文中引发的第一个异常(如果未引发异常,则为 nil)。

158
159
160
# File 'lib/rspec/core/example.rb', line 158
def exception
  @exception
end

#metadatavoid (只读)

返回与此示例关联的元数据对象。

163
164
165
# File 'lib/rspec/core/example.rb', line 163
def 
  @metadata
end

#reporterRSpec::Core::Reporter (只读)

返回示例的当前报告器。

返回

226
227
228
# File 'lib/rspec/core/example.rb', line 226
def reporter
  @reporter
end

实例方法详细信息

#descriptionvoid

返回提交给 example 或其别名(例如 specifyit 等)的字符串。如果未提交字符串(例如 it { is_expected.to do_something }),它将返回匹配器生成的(如果有)消息,否则返回包含示例位置的消息。

76
77
78
79
80
81
82
83
84
# File 'lib/rspec/core/example.rb', line 76
def description
  description = if [:description].to_s.empty?
                  location_description
                else
                  [:description]
                end
  RSpec.configuration.format_docstrings_block.call(description)
end

#duplicate_with(metadata_overrides = {}) ⇒Example

复制示例并使用提供的哈希覆盖元数据。

参数

  • metadata_overrides (Hash) (默认值: {})

    用于覆盖示例元数据的哈希

返回

  • (Example)

    具有修改元数据的示例副本

132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/rspec/core/example.rb', line 132
def duplicate_with(={})
   = .clone.merge()
  RSpec::Core::Metadata::RESERVED_KEYS.each do |reserved_key|
    .delete reserved_key
  end
  # don't clone the example group because the new example
  # must belong to the same example group (not a clone).
  #
  # block is nil in new_metadata so we have to get it from metadata.
  Example.new(example_group, description.clone,
              , [:block])
end

#example_groupvoid

返回提供运行此示例上下文的示例组类。

230
231
232
# File 'lib/rspec/core/example.rb', line 230
def example_group
  @example_group_class
end

#execution_resultExecutionResult

返回表示运行此示例的结果。

返回

53
# File 'lib/rspec/core/example.rb', line 53
 :execution_result

#file_pathString

返回定义此示例的文件的相对路径。

返回

  • (String)

    定义此示例的文件的相对路径。

56
# File 'lib/rspec/core/example.rb', line 56
 :file_path

#full_descriptionString

返回完整描述(包括所有父示例组的文档字符串)。

返回

  • (String)

    完整描述(包括所有父示例组的文档字符串)。

59
# File 'lib/rspec/core/example.rb', line 59
 :full_description

#idString

返回此示例的唯一 ID。在命令行中传递此 ID 以重新运行此确切示例。

返回

  • (String)

    此示例的唯一 ID。在命令行中传递此 ID 以重新运行此确切示例。

117
118
119
# File 'lib/rspec/core/example.rb', line 117
def id
  @id ||= Metadata.id_from()
end

#inspectvoid 也称为: to_s

提供此类的可读表示形式

220
221
222
# File 'lib/rspec/core/example.rb', line 220
def inspect
  "#<#{self.class.name} #{description.inspect}>"
end

#inspect_outputvoid

返回示例的描述,该描述始终包含位置。

87
88
89
90
91
92
93
# File 'lib/rspec/core/example.rb', line 87
def inspect_output
  inspect_output = "\"#{description}\""
  unless [:description].to_s.empty?
    inspect_output += " (#{location})"
  end
  inspect_output
end

#locationString

返回此示例的精确源位置,格式类似于 ./path/to/spec.rb:17

返回

  • (String)

    此示例的精确源位置,格式类似于 ./path/to/spec.rb:17

62
# File 'lib/rspec/core/example.rb', line 62
 :location

#location_rerun_argumentvoid

返回可以传递给 rspec 命令以重新运行此示例的位置参数。

96
97
98
99
100
101
102
103
104
# File 'lib/rspec/core/example.rb', line 96
def location_rerun_argument
  @location_rerun_argument ||= begin
    loaded_spec_files = RSpec.configuration.loaded_spec_files
    Metadata.ascending() do |meta|
      return meta[:location] if loaded_spec_files.include?(meta[:absolute_file_path])
    end
  end
end

#pendingBoolean

返回指示示例预期不会通过的标志。它将被运行,并将具有待处理结果(如果发生故障)或失败结果(如果没有发生故障)。

返回

  • (Boolean)

    指示示例预期不会通过的标志。它将被运行,并将具有待定结果(如果发生失败)或失败结果(如果没有发生失败)。

66
# File 'lib/rspec/core/example.rb', line 66
 :pending

#pending?Boolean

返回

  • (Boolean)
234
235
236
# File 'lib/rspec/core/example.rb', line 234
def pending?
  !!pending
end

#rerun_argumentvoid

已弃用。

请使用 #location_rerun_argument 替代。

注意

如果有多个由此位置标识的示例,它们将使用 #id 重新运行,但此方法仍将返回位置(这就是它被弃用的原因!)。

返回可以传递给 rspec 命令以重新运行此示例的位置参数。

111
112
113
# File 'lib/rspec/core/example.rb', line 111
def rerun_argument
  location_rerun_argument
end

#run(example_group_instance, reporter) ⇒void

此方法是私有 API 的一部分。如果可能,您应该避免使用此方法,因为它可能会在将来被删除或更改。

RSpec::Core::ExampleGroup 实例的上下文中,对构造函数传递的代码块执行 instance_exec。

参数

  • example_group_instance

    ExampleGroup 子类的实例

246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/rspec/core/example.rb', line 246
def run(example_group_instance, reporter)
  @example_group_instance = example_group_instance
  @reporter = reporter
  RSpec.configuration.configure_example(self, hooks)
  RSpec.current_example = self
  start(reporter)
  Pending.mark_pending!(self, pending) if pending?
  begin
    if skipped?
      Pending.mark_pending! self, skip
    elsif !RSpec.configuration.dry_run?
      with_around_and_singleton_context_hooks do
        begin
          run_before_example
          RSpec.current_scope = :example
          @example_group_instance.instance_exec(self, &@example_block)
          if pending?
            Pending.mark_fixed! self
            raise Pending::PendingExampleFixedError,
                  'Expected example to fail since it is pending, but it passed.',
                  [location]
          end
        rescue Pending::SkipDeclaredInExample => _
          # The "=> _" is normally useless but on JRuby it is a workaround
          # for a bug that prevents us from getting backtraces:
          # https://github.com/jruby/jruby/issues/4467
          #
          # no-op, required metadata has already been set by the `skip`
          # method.
        rescue AllExceptionsExcludingDangerousOnesOnRubiesThatAllowIt => e
          set_exception(e)
        ensure
          RSpec.current_scope = :after_example_hook
          run_after_example
        end
      end
    end
  rescue Support::AllExceptionsExceptOnesWeMustNotRescue => e
    set_exception(e)
  ensure
    @example_group_instance = nil # if you love something... let it go
  end
  finish(reporter)
ensure
  execution_result.ensure_timing_set(clock)
  RSpec.current_example = nil
end

#skipBoolean

返回将导致示例不运行的标志。ExecutionResult 状态将为 :pending

返回

  • (Boolean)

    将导致示例不运行的标志。ExecutionResult 状态将为 :pending

69
# File 'lib/rspec/core/example.rb', line 69
 :skip

#skipped?Boolean

返回

  • (Boolean)
238
239
240
# File 'lib/rspec/core/example.rb', line 238
def skipped?
  !!skip
end