Come si simulano i parametri durante il test del setter di un modello Rails?
-
01-07-2019 - |
Domanda
Dato il codice da Forma complessa parte III come faresti per testare l'attributo virtuale?
def new_task_attributes=(task_attributes)
task_attributes.each do |attributes|
tasks.build(attributes)
end
end
Attualmente sto provando a testarlo in questo modo:
def test_adding_task_to_project
p = Project.new
params = {"new_tasks_attributes" => [{ "name" => "paint fence"}]}
p.new_tasks_attributes=(params)
p.save
assert p.tasks.length == 1
end
Ma ricevo il seguente errore:
NoMethodError:Metodo indefinito `Stringify_keys! ' per "new_tasks_attributes": stringa
Qualsiasi suggerimento su come migliorare questo test sarebbe molto apprezzato.
Soluzione
Sembra che new_task_attributes= si aspetti un array di hash, ma tu gli stai passando un hash.Prova questo:
def test_adding_task_to_project
p = Project.new
new_tasks_attributes = [{ "name" => "paint fence"}]
p.new_tasks_attributes = (new_tasks_attributes)
p.save
assert p.tasks.length == 1
end
Altri suggerimenti
Possiamo vedere l'intera traccia dello stack?Dove pensa String#stringify_keys!viene chiamato?
Inoltre, params mi sembra strano.task.build() si aspetta un input come questo: ["new_tasks_attribute", {"name" => "paint fence"}]
?
In caso contrario, forse vuoi davvero Hash#each_key() invece di Hash#each()?
Hai bisogno di più dati.Inoltre, potresti prendere in considerazione un tag Ruby per accompagnare il tuo tag Rails.