关于ruby:在RSpec-2.11中使用带有`expect`的隐式`subject`

Using implicit `subject` with `expect` in RSpec-2.11

使用rspec-2.11中新的expect语法,如何使用隐式subject?有没有像下面这样显式引用subject更好的方法?

1
2
3
4
5
describe User do
  it 'is valid' do
    expect(subject).to be_valid    # <<< can `subject` be implicit?
  end
end

如果将RSpec配置为禁用should语法,则仍然可以使用旧的单行语法,因为这并不涉及将should添加到每个对象中:

1
2
3
describe User do
  it { should be_valid }
end

我们简要地讨论了另一种单线语法,但是由于不需要它而决定反对它,并且我们认为它可能会增加混乱。但是,如果您喜欢它的读取方式,则可以轻松地自己添加它:

1
2
3
4
5
6
7
8
RSpec.configure do |c|
  c.alias_example_to :expect_it
end

RSpec::Core::MemoizedHelpers.module_eval do
  alias to should
  alias to_not should_not
end

就位后,您可以这样写:

1
2
3
describe User do
  expect_it { to be_valid }
end


使用Rspec 3.0,您可以按此处所述使用is_expected

1
2
3
4
5
6
7
8
9
10
11
12
describe Array do
  describe"when first created" do
    # Rather than:
    # it"should be empty" do
    #   subject.should be_empty
    # end

    it { should be_empty }
    # or
    it { is_expected.to be_empty }
  end
end


一个人可以使用新的命名主题语法,尽管它不是隐式的。

1
2
3
4
5
6
7
describe User do
  subject(:author) { User.new }

  it 'is valid' do
    expect(author).to be_valid
  end
end