Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...