在测试 Rails 模型的 setter 时如何模拟参数?

发布于 2024-07-06 03:02:38 字数 672 浏览 5 评论 0原文

给定复杂表单第三部分中的代码,您将如何测试虚拟属性?

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

我目前正在尝试像这样测试它:

  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

但我收到以下错误:

NoMethodError:未定义方法“stringify_keys!” 对于“new_tasks_attributes”:字符串

任何有关改进此测试的建议将不胜感激。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

Smile简单爱 2024-07-13 03:02:38

看起来 new_task_attributes= 需要一个散列数组,但您向它传递了一个散列。 尝试这个:

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

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
暗地喜欢 2024-07-13 03:02:38

我们可以看到整个堆栈跟踪吗? 它认为 String#stringify_keys! 在哪里? 正在被呼叫吗?

另外,params 对我来说看起来很奇怪。 tasks.build() 是否期望这样的输入: ["new_tasks_attribute", {"name" => “油漆栅栏”}]

如果没有,也许您实际上想要 Hash#each_key() 而不是 Hash#each()?

需要更多数据。 另外,您可能会考虑将 Ruby 标签与 Rails 标签一起使用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文