简体   繁体   English

使用Rspec测试将Ruby对象转换为json对象

[英]Test conversion of Ruby object into a json object with Rspec

I have an object with say four attributes; 我有一个具有四个属性的对象。

Object
attr1, attr2, attr3, attr4

I need to send this info to another app for Data Science reasons. 由于数据科学的原因,我需要将此信息发送到另一个应用程序。 I create a method that does the mapping: 我创建一个执行映射的方法:

def convert_for_elastic_search
    {
        name_attr1: @object.attr1,
        name_attr2: @object.attr2,
        name_attr3: @object.attr3
    }
end

How can I test this method with RSpec? 如何使用RSpec测试此方法? I can't mock and I don't want to hardcode the values, since they come from Factory Bot. 我不能嘲笑,也不想对值进行硬编码,因为它们来自Factory Bot。

Which is the better approach? 哪种方法更好?

The best would be to somehow obtain a reference to @object . 最好的办法是以某种方式获取对@object的引用。 If it is created using a create() call then you can override attributes from the factory. 如果是使用create()调用创建的,则可以覆盖工厂的属性。

If you can't set the values directly then you could create expectations that validate that the 'mapped' values match the source values. 如果无法直接设置值,则可以创建期望来验证“映射”值与源值匹配。

object { FactoryBot.create(:object) }
subject { FactoryBot.create(:mapper, object: object) }
result = subject.convert_for_elastic_search
expect(result[:name_attr1]).to eq object.attr1
expect(result[:name_attr2]).to eq object.attr2
expect(result[:name_attr3]).to eq object.attr3

Of course if you are setting up the spec as shown above then it would be trivial to set hardcoded values. 当然,如果您按照上面所示设置规格,那么设置硬编码值将是微不足道的。 ie FactoryBot.create(:object, attr1: 'val1') . FactoryBot.create(:object, attr1: 'val1') In which case you can just expect 'val1'. 在这种情况下,您只能期待'val1'。

If object is not accessible as shown above then you'd need a way to get a reference to it, perhaps the mapper (subject) exposes this somehow. 如果无法如上所示访问object ,则您需要一种获取对它的引用的方法,也许映射器(主题)以某种方式公开了该对象。

If you really can't get at @object then perhaps just testing the value is present & of the correct data type would be enough to validate the mapping process. 如果您真的无法使用@object那么仅测试存在的值和正确的数据类型就足以验证映射过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM