views:

468

answers:

2

Given the code from the Complex Form part III how would you go about testing the virtual attribute?

  def new_task_attributes=(task_attributes)
    task_attributes.each do |attributes|
      tasks.build(attributes)
    end
  end

I am currently trying to test it like this:

  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

But I am getting the following error:

NoMethodError: undefined method `stringify_keys!' for "new_tasks_attributes":String

Any suggestions on improving this test would be greatly appreciated.

+3  A: 

It looks as if new_task_attributes= is expecting an array of hashes, but you're passing it a hash. Try this:

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
Jason Wadsworth
A: 

Can we see the whole stack trace? Where does it think String#stringify_keys! is being called?

Also, params looks odd to me. Is tasks.build() expecting input like this: ["new_tasks_attribute", {"name" => "paint fence"}] ?

If not, maybe you actually want Hash#each_key() instead of Hash#each()?

Need more data. Also, you might consider a Ruby tag to accompany your Rails tag.

Ben Hamill