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

前端 未结 3 710
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 06:50

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 s

相关标签:
3条回答
  • 2020-12-08 07:12

    One could use the new named subject syntax, although it's not implicit.

    describe User do
      subject(:author) { User.new }
    
      it 'is valid' do
        expect(author).to be_valid
      end
    end
    
    0 讨论(0)
  • 2020-12-08 07:17

    With Rspec 3.0 you can use is_expected as described here.

    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
    
    0 讨论(0)
  • 2020-12-08 07:25

    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
    
    0 讨论(0)
提交回复
热议问题