【问题标题】:Rails 3: Convert a fixture to a set of ActionController::ParametersRails 3:将夹具转换为一组 ActionController::Parameters
【发布时间】:2013-02-22 15:36:20
【问题描述】:

有没有办法将fixture 转换为一组ActionController::Parameters?

例如:

# contacts.yml

dan:
  first_name: Dan
  last_name: Gebhardt
  email: dan@example.com
  notes: Writes sample code without tests :/

joe:
  first_name: Joe
  last_name: Blow
  email: joe@example.com
  notes: Lousy plumber

# contacts_test.rb

@dan = contacts(:dan)
# create params that represent Dan?
@dan_as_params = ActionController::Parameters.new(???)

任何和所有的帮助表示赞赏。

【问题讨论】:

    标签: ruby-on-rails ruby testing fixtures


    【解决方案1】:

    您可以将对象转换为 json 并返回到包含正确参数键的哈希:

    h= Hash[*JSON.load(@dan.to_json).map{ |k, v| [k.to_sym, v] }.flatten]
    params= {contact: h}
    

    更新:

    你也可以使用 JSON.parse

    dan= Hash[*JSON.parse(@dan.to_json, symbolize_names: true).flatten]
    params= {contact: dan}
    

    它有自己的内部方式将 json 键转换为符号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      相关资源
      最近更新 更多