加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – RSpec’Expect’语法和惯用属性规范

发布时间:2020-12-16 19:24:26 所属栏目:百科 来源:网络整理
导读:这应该有一个简单的答案,但我很难找到它(已经检查了RSpec文档,使用RSpec的日常测试,Google结果).在我的模型规范中,我喜欢包括基本属性规范如下: describe Foo do describe "basic attributes" do before { @foo = create(:foo) } subject { @foo } it { sho
这应该有一个简单的答案,但我很难找到它(已经检查了RSpec文档,使用RSpec的日常测试,Google结果).在我的模型规范中,我喜欢包括基本属性规范如下:
describe Foo do
  describe "basic attributes" do
    before { @foo = create(:foo) }
    subject { @foo }

    it { should be_valid }
    it { should respond_to(:color) }
    it { should respond_to(:height) }
    it { should respond_to(:some_other_attribute) }
    it { should respond_to(:you_get_the_idea) }
    ...

我喜欢这些规范,因为如果我的工厂和/或模型中有某种错误,这些规范可以帮助我快速找出错误.

我已经将expect语法合并到所有其他规范中,我喜欢它如何读取,但是如何在这里使用它?一个选择可能是

expect(@foo).to respond_to(:color)

另一个可能是

expect(it).to respond_to(:color)

前者涉及使用应用语法避免的重复,但后者对我来说看起来很奇怪(这可能只是我).

我意识到这个问题更多的是风格,而不是功能*,但是我们的Ruby开发人员都认真对待风格,我想坚持标准的做法,并且具有可读性,惯用的代码.任何帮助是赞赏.谢谢.

更新:我的建议选项都没有实际工作,顺便说一句.他们都抛出未定义的方法’expect’错误.现在我真的很困惑!

考虑到这个错误,我意识到这是因为上面的规范在一行内.那么混淆就是如何用预期的语法写一个单行的块?鉴于此次更新,这个问题非常关于功能,我很高兴听到他人的想法.

4/2015更新

rspec> 3.0已经添加了另一种处理方式,这听起来像是rspec?> 4.0将会消除应用语法.每个Myron大师:

Some users have expressed confusion about how this should relates to the expect syntax and if you can continue using it. It will continue to be available in RSpec 3 (again,regardless of your syntax configuration),but we’ve also added an alternate API that is a bit more consistent with the expect syntax:

describe Post do
  it { is_expected.to allow_mass_assignment_of(:title) }
end

is_expected is defined very simply as expect(subject) and also supports negative expectations via is_expected.not_to matcher.
[…]
In RSpec 3,we’ve kept the should syntax,and it is available by default,but you will get a deprecation warning if you use it without explicitly enabling it. This will pave the way for it being disabled by default (or potentially extracted into a seperate gem) in RSpec 4,while minimizing confusion for newcomers coming to RSpec via an old tutorial.

解决方法

RSPec核心提供商之一的Myron Marston解释说 here您仍然应该使用
it { should be_cool }

如果您已禁用应用程序语法,则他将提供一个解决方案来等待expect_it:

06001

With this in place,you could write this as:

06002

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读