Search code examples
ruby-on-railsunit-testingtestingtesting-strategies

How do you mock params when testing a Rails model's setter?


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.


Solution

  • 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