【问题标题】:Comparing attributes/property of API response with local stub将 API 响应的属性/属性与本地存根进行比较
【发布时间】:2014-08-10 07:16:19
【问题描述】:

我的model 中有一个方法,它返回下面的object,我将其转换为json。

got: "{\"@type\":\"accountResource\",\"createdAt\":\"2014-08-07T14:31:58\",\"createdBy\":2,\"updatedAt\":\"2014-08-07T14:31:58\",\"updatedBy\":2,\"accountid\":2055,\"name\":\"Test\",\"description\":\"Something about Test\",\"disabled\":false}"

我如何将 attributes 单独与我的 stub 进行比较。

以下是我的规格

it "can create an account" do    
    acc = FactoryGirl.create(:account, name: "Test", 
                         description: "Something about Test");
    create_account = Account.create(account: acc)
    expect(create_account.to_json).to eq(what)     
end

我需要与我的本地 json 进行比较,从 API 返回的 json 与我在本地的 attributes 相同。我不想检查值,只检查 attributes 是否相同。

【问题讨论】:

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


    【解决方案1】:

    我没有看到任何请求。我想,你想要的会是这样的:

    it "can create an account" do
      attrs = Factory.attributes_for(:account)
      account = Factory.create(:account, attrs) # instead of this you should do you request
      expect(JSON.parse(account.to_json)).to eq(attrs)
    end
    

    如果请求期望将是下一个:

    expect(JSON.parse(response.body)).to eq(attrs)
    

    如果你想跳过一些像 created_at 这样的属性,你需要一个这样的自定义匹配器:

    RSpec::Matchers.define :eq_attributes do |sample|
      match do |actual|
        sample.reject { |k, _| %w(id updated_at created_at).include? k }.all? { |k, v| actual[k] == v }
      end
    end
    

    它会跳过idupdated_atcreated_at。有了它,期待下一个:

    expect(JSON.parse(response.body)).to eq_attributes(attrs)
    

    【讨论】:

    • expect(JSON.parse(response.body)) 到 eq(attrs) 会不会同时检查键和值?
    • 只需获取关键数组并进行比较。对于匹配器expect(actual.keys).to match_array(sample.keys)
    • There你可以找到更多的匹配器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    • 2015-05-12
    • 1970-01-01
    相关资源
    最近更新 更多