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

ruby – 在rspec中匹配参数的属性值

发布时间:2020-12-17 01:50:40 所属栏目:百科 来源:网络整理
导读:有没有办法在rspec中匹配参数的属性值?检查 the documentation看起来还有其他可用的匹配器,例如任何东西,an_instance_of和hash_including – 但没有检查对象属性的值. 示例 – 假设我有此实例方法: class DateParser def parse_year(a_date) puts a_date.y
有没有办法在rspec中匹配参数的属性值?检查 the documentation看起来还有其他可用的匹配器,例如任何东西,an_instance_of和hash_including – 但没有检查对象属性的值.

示例 – 假设我有此实例方法:

class DateParser
  def parse_year(a_date)
    puts a_date.year
  end
end

然后我可以这样写一个期望:

dp = DateParser.new
expect(dp).to receive(:parse_year).with(some_matcher)

我希望some_matcher检查parse_year是否使用具有值为2014的属性年的任何对象进行调用.这是否可以使用rspec中的开箱即用参数匹配,或者是否必须使用自定义参数匹配书面?

解决方法

您可以传递一个块并设置对块内参数的期望:

describe DateParser do
  it "expects a date with year 2014" do
    expect(subject).to receive(:parse_year) do |date|
      expect(date.year).to eq(2014)
    end
    subject.parse_year(Date.new(2014,1,1))
  end
end

(编辑:李大同)

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

    推荐文章
      热点阅读