【问题标题】:RSpec: difference between is_expect and expectRSpec:is_expect和expect之间的区别
【发布时间】:2019-04-30 13:33:13
【问题描述】:

我在这里有两个规格:

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

为什么会这样? 提前非常感谢!

【问题讨论】:

  • 您也可以考虑使用subject(:house) { .... }subjecthouse 定义为相同的东西。但是,鉴于您的帖子中缺少上下文,我不确定该语法在此示例中是否有效。

标签: ruby-on-rails ruby rspec rspec-rails


【解决方案1】:

is_expected 被简单地定义为 expect(subject),专为您使用 rspec-expectations 及其新的基于期望的语法而设计。

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

由于被测对象是house 而不是subject,我假设subject 未初始化,因此设置为默认值(described_class.new)。 is_expected 调用这个默认主题的期望。

要使用is_expected,初始化主题:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2020-05-10
    • 2014-09-20
    • 2010-10-28
    相关资源
    最近更新 更多