在测试 Rails 模型的 setter 时如何模拟参数?
给定复杂表单第三部分中的代码,您将如何测试虚拟属性?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来 new_task_attributes= 需要一个散列数组,但您向它传递了一个散列。 尝试这个:
It looks as if new_task_attributes= is expecting an array of hashes, but you're passing it a hash. Try this:
我们可以看到整个堆栈跟踪吗? 它认为 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.