模块:RSpec::Core::MemoizedHelpers

包含于
ExampleGroup
定义于
lib/rspec/core/memoized_helpers.rb

概述

此模块包含在 ExampleGroup 中,使这些方法可以在示例块中调用。

另请参阅

定义于命名空间下

模块: ClassMethods

实例方法摘要 折叠

实例方法详情

#is_expectedvoid

注意

这只有在您使用 rspec-expectations 时才有效。

subject 包裹在 expect 中,使其成为期望的目标。旨在为单行代码提供良好的可读性。

示例


describe [1, 2, 3] do
  it { is_expected.to be_an Array }
  it { is_expected.not_to include 4 }
end

另请参阅

120
121
122
# File 'lib/rspec/core/memoized_helpers.rb', line 120
def is_expected
  expect(subject)
end

#should(matcher = nil, message = nil) ⇒void

注意

这只有在您使用 rspec-expectations 时才有效。

注意

如果您使用的是 RSpec 的新型基于期望的语法,您可能希望使用 is_expected.to 而不是 should

should 在没有显式接收者的情况下被调用时,调用会被委托给 subject 返回的对象。与隐式主题结合,这支持非常简洁的表达式。

示例


RSpec.describe Person do
  it { should be_eligible_to_vote }
end

另请参阅

80
81
82
83
# File 'lib/rspec/core/memoized_helpers.rb', line 80
def should(matcher=nil, message=nil)
  enforce_value_expectation(matcher, 'should')
  RSpec::Expectations::PositiveExpectationHandler.handle_matcher(subject, matcher, message)
end

#should_not(matcher = nil, message = nil) ⇒void

注意

这只有在您使用 rspec-expectations 时才有效。

注意

如果您使用的是 RSpec 的新型基于期望的语法,您可能希望使用 is_expected.to_not 而不是 should_not

should 相同,should_not 会委托给示例组的主题(隐式或显式)。

示例


RSpec.describe Person do
  it { should_not be_eligible_to_vote }
end

另请参阅

100
101
102
103
# File 'lib/rspec/core/memoized_helpers.rb', line 100
def should_not(matcher=nil, message=nil)
  enforce_value_expectation(matcher, 'should_not')
  RSpec::Expectations::NegativeExpectationHandler.handle_matcher(subject, matcher, message)
end

#subjectvoid

注意

subject 由 Joe Ferris 贡献,以支持 shoulda matchers 采用的单行代码语法

RSpec.describe Widget do
  it { is_expected.to validate_presence_of(:name) }
  # or
  it { should validate_presence_of(:name) }
end

虽然以下示例演示了如何在示例中显式使用 subject,但我们建议您定义一个具有揭示意图名称的方法。

注意

由于 subject 旨在创建在每个示例之间重置的状态,而 before(:context) 旨在设置在示例组中所有示例之间共享的状态,因此 subject 打算在 before(:context) 钩子中使用。

示例


# Explicit declaration of subject.
RSpec.describe Person do
  subject { Person.new(:birthdate => 19.years.ago) }
  it "should be eligible to vote" do
    subject.should be_eligible_to_vote
    # ^ ^ explicit reference to subject not recommended
  end
end
# Implicit subject => { Person.new }.
RSpec.describe Person do
  it "should be eligible to vote" do
    subject.should be_eligible_to_vote
    # ^ ^ explicit reference to subject not recommended
  end
end
# One-liner syntax - expectation is set on the subject.
RSpec.describe Person do
  it { is_expected.to be_eligible_to_vote }
  # or
  it { should be_eligible_to_vote }
end

另请参阅

57
58
59
60
61
62
# File 'lib/rspec/core/memoized_helpers.rb', line 57
def subject
  __memoized.fetch_or_store(:subject) do
    described = described_class || self.class..fetch(:description_args).first
    Class === described ? described.new : described
  end
end