新手问题 RSpec 疑问: 为什么这里的 subject 不是最近的那个类呢?

fsword · 2014年07月03日 · 最后由 algo31031 回复于 2014年07月03日 · 1830 次阅读

源码如下:

$ cat spec/nested_subject_spec.rb 
class ArrayWithOneElement < Array
  def initialize(*)
    super
    unshift "first element"
  end
end

describe Array do
  describe ArrayWithOneElement do
    context "referenced as subject" do
      it "contains one element" do
        expect(subject).to include("first element")
      end
    end
  end
end

下面是执行结果:

$ rspec spec/nested_subject_spec.rb 
F

Failures:

  1) Array ArrayWithOneElement referenced as subject contains one element
     Failure/Error: expect(subject).to include("first element")
       expected [] to include "first element"
     # ./spec/nested_subject_spec.rb:12:in `block (4 levels) in <top (required)>'

Finished in 0.00099 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/nested_subject_spec.rb:11 # Array ArrayWithOneElement referenced as subject contains one element

官方网站上也说应该是 pass 的,但我执行就 fail 了,不得其解

推测可能和 rspec 版本有关

#1 楼 @algo31031 果然

$ gem search rspec -l

*** LOCAL GEMS ***

rspec (2.14.1)
rspec-core (2.14.8, 2.14.7)
rspec-expectations (2.14.5, 2.13.0)
rspec-mocks (2.14.6, 2.14.5)
rspec-rails (2.14.1)

$ gem install rspec
Fetching: rspec-3.0.0.gem (100%)
Successfully installed rspec-3.0.0
...
Done installing documentation for rspec, rspec-core, rspec-expectations, rspec-mocks, rspec-support after 4 seconds
5 gems installed
~/projects/mine/larrow[2.1.1]
$ gem search rspec -l

*** LOCAL GEMS ***

rspec (3.0.0, 2.14.1)

$ rspec 
.....

Finished in 0.00174 seconds (files took 0.10403 seconds to load)
5 examples, 0 failures

需要 登录 后方可回复, 如果你还没有账号请 注册新账号