简体   繁体   English

Rails ActiveRecord serialize方法在测试环境中不起作用

[英]Rails ActiveRecord serialize method doesn't work in test environment

I've got a problem with deserialization of ActiveRecord serialize method in my tests. 我在测试中遇到了ActiveRecord 序列化方法的反序列化问题。
It just gives me pure String instead of my data Array. 它只是给我纯String而不是我的数据Array。

Example: 例:

User > ActiveRecord::Base
   serialize :roles, Array
end

Console: 安慰:

u = User.new
u.roles = ["admin", "support"]
u.save
# => true

User.first.roles
# => ["admin", "support"]

In test environment: 在测试环境中:

User.first.roles
# => "--- \n- admin\n- support\n"

it is a String. 它是一个字符串。 It seems that YAML serialize is not working there but I have no idea what to do to get it working. 似乎YAML序列化不在那里工作,但我不知道如何使其工作。

I was already trying to figure it out with this , this , this and this , but with no luck. 我已经试图与弄明白这个这个这个这个 ,但没有运气。

Any advice would be greatly appreciated. 任何建议将不胜感激。
Martin 马丁

After all to bypass this I needed to call the data in database directly without involvement of "serialize" AR method. 毕竟要绕过这个,我需要直接调用数据库中的数据而不涉及“序列化”AR方法。

YAML::load(User.first.roles_before_type_cast)

And now test environment also directly parses the data and give me correct roles Array. 而现在测试环境也直接解析数据并给我正确的角色Array。

I dont know if it solves your problem, but you can always get back the array from the string using 我不知道它是否解决了你的问题,但你总是可以从字符串中取回数组

YAML::load("--- \n- admin\n- support\n")
# => ["admin", "support"]

So, in your test environment, you should do 因此,在您的测试环境中,您应该这样做

YAML::load(User.first.roles)

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

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