代码之家  ›  专栏  ›  技术社区  ›  noloman

RSPEC:预期与预期的区别

  •  1
  • noloman  · 技术社区  · 6 年前

    我这里有两种规格:

    it 'is not an included preferred gender' do
      house.preferred_gender = 3
      is_expected.not_to be_valid
    end
    
    it 'is an included preferred gender' do
      house.preferred_gender = 2
      expect(house).to be_valid
    end
    

    我不明白的是如果我在第二个规范中替换 expect(house).to be_valid 对于 is_expected.to be_valid ,然后我的测试失败:

    失败:

    1) House preferred gender is an included preferred gender
         Failure/Error: is_expected.to be_valid
           expected #<House id: nil, rent: nil, deposit: nil, description: nil, preferred_gender: nil, created_at: nil, updated_at: nil, available_at: nil, user_id: nil, lease_length: nil, built_in: nil> to be valid, but got errors: User must exist, Rent can't be blank, Rent is not a number, Preferred gender can't be blank, Preferred gender is not included in the list, Available at can't be blank
         # ./spec/models/house_spec.rb:94:in `block (3 levels) in <main>'
    
    Finished in 16.27 seconds (files took 3.02 seconds to load)
    52 examples, 1 failure
    

    为什么会这样? 提前多谢!

    1 回复  |  直到 6 年前
        1
  •  2
  •   mrzasa    6 年前

    is_expected 简单定义为expect(subject),设计用于使用rspec预期及其更新的基于expect的语法时。

    https://relishapp.com/rspec/rspec-core/docs/subject/one-liner-syntax

    因为测试对象是 house subject 我认为 主题 未初始化,因此设置为defaul( described_class.new ) 伊斯预期 调用此默认主题的期望值。

    使用 伊斯预期 ,初始化主题:

    describe House do
       subject { House.new(...) } # or build :house if you use FactoryBot
       # ...
    end