问题描述
使用 rspec-2.11 中新的 expect
语法,如何使用隐式 subject
?有没有比显式引用 subject
更好的方法,如下所示?
With the new expect
syntax in rspec-2.11, how is it possible to use the implicit subject
? Is there a better way than explicitly referencing subject
, like below?
describe User do
it 'is valid' do
expect(subject).to be_valid # <<< can `subject` be implicit?
end
end
推荐答案
如果您将 RSpec 配置为禁用 should
语法,您仍然可以使用旧的单行语法,因为那不会涉及应该
被添加到每个对象:
If you configure RSpec to disable the should
syntax, you can still use the old one-liner syntax, since that doesn't involve should
being added to every object:
describe User do
it { should be_valid }
end
我们简要讨论了另一种单行语法,但决定反对它,因为它不需要,我们觉得它可能会增加混乱.但是,如果您更喜欢它的读取方式,您可以自己轻松添加:
We briefly discussed an alternate one-liner syntax, but decided against it since it wasn't needed and we felt like it might add confusion. You can, however, easily add this yourself if you prefer how it reads:
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
有了这个,你可以把它写成:
With this in place, you could write this as:
describe User do
expect_it { to be_valid }
end
这篇关于在 RSpec-2.11 中使用带有“expect"的隐式“subject"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!