我有一个文章类的Rails单元测试,我有一个断言来测试创建!方法。我想基本上从.yml数据创建对象。像这样:
在我的yaml文件中... / test / fixtures / articles.yml:
one:
id: 1
title: MyText
abstract: MyText
place: MyString
subject: MyString
在article_test.rb中:
def test_create_a_new_article
assert Article.create!(articles(:one))
end
我不断收到NoMethodError: undefined method
stringify_keys' for#< \ Article:0x0000010819b640> which I'm not surprised by, but how do call create! from the instance of Article created by articles(:one)? I'm instantiating Article in my running code by passing params in a hash. Would be great if I could just do something like: a
ssert Article.create!(articles(:one).to_hash)`
感谢您的帮助。
答案 0 :(得分:2)
当您调用文章(:1)时,您将获得具有在fixture中定义的属性的Article对象。这意味着您可以按原样使用它。
articles(:one).some_method
或将其分配给变量
article = articles(:one)
基本上是导轨魔术
修改
Article.create articles(:one).attributes.except(" id")
不确定是否需要排除ID
答案 1 :(得分:0)
经过大量的实验,似乎现在有了直接的方法来做到这一点。您可以随时直接加载yaml:
def test_create_a_new_article
attributes = YAML.load_file(File.join fixture_path, 'articles.yml')['one']
assert Article.create!(articles(:one))
end