【问题标题】:How can I do request tests with Grape Entity?如何使用 Grape Entity 进行请求测试?
【发布时间】:2014-10-26 02:43:37
【问题描述】:

响应正文返回“带有葡萄实体的格式化json”,但first_prefered返回的是完整对象(json格式)。

如何转换 first_prefered 对象以使用葡萄实体获取暴露的字段?

FeaturedHomekeeperResponseEntity:

module API::V1::Entities
  class FeaturedHomekeeperResponseEntity < Grape::Entity
    expose :id, documentation: { type: 'integer', desc: 'ID' }
    expose :featured_type, documentation: { type: 'string', desc: 'Featured Type' }
  end
end

测试:

let(:address) { Fabricate(:address) }

      it 'should return the first prefered homekeeper of an address' do
        first_prefered = Fabricate(:featured_homekeeper_as_first_prefered, address: address)

        get "/api/v1/addresses/#{address.id}/prefered/first"

        expect(json).to eq(YAML.load(first_prefered.to_json))
      end

【问题讨论】:

    标签: rspec grape-api grape-entity


    【解决方案1】:

    我认为您不应该使用 Grape::Entity 来格式化测试场景中的数据。因为这是一个验收/集成测试,它应该是从用户的角度编写的。它应该包含尽可能少的代码相关内容。恕我直言,您应该手动从 JSON 中选择键/值。

    【讨论】:

    • 我同意这一点。我认为你应该更明确地表达你想要断言的内容。 =)
    • 太棒了!我在想那个。但是我没有看到任何文章谈论这个。谢谢。
    【解决方案2】:

    Grape::Entity 类有一个表示方法。所以

    API::V1::Entities::FeaturedHomekeeperResponseEntity.represent first_prefered
    

    将返回演示者对象。

     API::V1::Entities::FeaturedHomekeeperResponseEntity.represent(first_prefered).to_json()
    

    应该返回你想要的json。

    【讨论】:

    • 感谢您的回答。
    猜你喜欢
    • 2018-01-15
    • 1970-01-01
    • 2011-06-28
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多