【问题标题】:How to compare an array in rspec如何比较rspec中的数组
【发布时间】:2018-04-07 12:11:56
【问题描述】:

您好,我正在使用 ruby​​-2.5.0 和 Rails 5 开发 RoR 项目。我在控制器上有一个方法,它返回一个数组,该数组包含一个字符串和一个接收模型的对象,如下所示:

["IGA", #<Reciept id: 1, name: "IGA", reciept_date: "2006-02-18 16:25:00", user_id: 1, created_at: "2018-04-07 11:53:33", updated_at: "2018-04-07 11:53:33">]

在我的 rspec 中,我想按如下方式比较这个数组:-

it { expect(described_class.find_store(params,user_id)).to eq(["IGA", #<Reciept id: 1, name: "IGA", reciept_date: "2006-02-18 16:25:00", user_id: 1, created_at: "2018-04-07 11:53:33", updated_at: "2018-04-07 11:53:33">]) }

它给出了语法错误,因为数组内部有一个“#”符号,因此它与我的代码相匹配。请帮助我如何比较这个数组。提前致谢。

【问题讨论】:

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


    【解决方案1】:

    尝试以下方法:

    it { expect(described_class.find_store(params,user_id)).to eq(["IGA", Reciept.find(1)]) }
    

    【讨论】:

      【解决方案2】:

      要比较数组而不考虑排序,请尝试match_array

      it { expect(described_class.find_store(params,user_id)).to match_array(["IGA", Reciept.find(1)]) }
      

      无论"IGA" 还是Receipt 先出现,这都会通过。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 2011-02-05
        • 1970-01-01
        相关资源
        最近更新 更多