测试 expect 无法和 have 相搭配

jzlikewei · 2014年04月05日 · 最后由 codemonkey 回复于 2016年03月03日 · 2910 次阅读

Failure/Error: expect (assigns(:devices)).to have(4).devices TypeError: can't convert RSpec::Matchers::BuiltIn::Have to Integer (RSpec::Matchers::BuiltIn::Have#to_int gives RSpec::Matchers::BuiltIn::Have)

改成 (assigns(:devices)).should have(4).devices 就没问题了 有人知道是什么情况么?

Using rspec-core (2.14.8) Using rspec-expectations (2.14.5) Using rspec-mocks (2.14.6) Using rspec-rails (2.14.2)

assigns(:devices).should(have(4).devices)

#1 楼 @ruohanc 我的意思是 expect (assigns(:devices)).to have(4).devices 为什么无法正常工作? should 的语法不是说未来要移除了么

expect(assigns(:devices)).to have(4).devices

#3 楼 @ruohanc 括号的问题?中间不能加空格么

嗯?你能给我一个方法调用后面带空格然后再来一个括号,ruby 不报错的例子么?

https://relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/have-n-items-matcher

class String
  def words
    split(' ')
  end
end

 describe String.new('hello') do
      it {
        should have(5).words }
    end

https://relishapp.com/rspec/rspec-expectations/v/3-4/docs/custom-matchers/define-a-custom-matcher#define-aliases-for-your-matcher

require 'rspec/expectations'

RSpec::Matchers.define :have_7_fingers do
  match do |thing|
    thing.fingers.length == 7
  end
end

class Thing
  def fingers; (1..7).collect {"finger"}; end
end

RSpec.describe Thing do
  it { is_expected.to have_7_fingers }
end
需要 登录 后方可回复, 如果你还没有账号请 注册新账号