【问题标题】:Integration test for has_one relationship failinghas_one 关系的集成测试失败
【发布时间】:2015-05-18 21:23:19
【问题描述】:

我在用户和组织之间有关系:

User migration file:     t.references :organization, index: true, foreign_key: true
                         t.string :xml_file, null: false
User model file:         belongs_to :organization
Organization model file: has_one :user

用户模型包含一个变量xml_file,它是一个存储在某处的文件(尚未编写该控制器方法)。我正在尝试编写集成测试:

def setup
  emptymap = fixture_file_upload('test/fixtures/empty.xml', 'application/xml', :binary)  # I have uploaded this file in the fixtures directory.
  @organization = organizations(:one)  # Which is in the organizations fixtures file.
  @user = @organization.users.build(xml_file: emptymap)
end

test "should be valid" do
  assert @user.valid?
end

这会产生错误(参考测试中的@user 行):

NoMethodError: undefined method `users' for #<Organization:0x00000008a41d18>

如果我将def setup 中的@user 行更改为@user = @organization.user.build(xml_file: emptymap),则会生成错误消息:NoMethodError: undefined methodbuild' for nil:NilClass`。所以好像也不是这样。

知道我在这里做错了什么吗?

【问题讨论】:

  • @organization.user.build 不是users
  • 那么它仍然会产生错误信息:NoMethodError: undefined method 'build' for nil:NilClass
  • 其实是@organization.build_user

标签: ruby-on-rails ruby ruby-on-rails-4 integration-testing


【解决方案1】:

build 在您使用时仅适用于集合。因为你在 User belongs_to :organizationOrganization 有一个 :user` 你没有集合,所以你有一对一的关系。

所以正确的属性是@organization.user

还有一种特殊的一对一关系格式...build_(something)

@organization.build_user(xml_file: emptymap)

【讨论】:

  • 感谢您解决了原来的问题。测试还没有通过,结果是因为模型验证(如果我删除它,测试通过):validate :xml_file_formatprivate def xml_file_formaterrors.add(:xml_file, "File format error") unless (xml_file.match(/\.xml\z/))end。你不会碰巧知道为什么?
  • 因为根据该验证文件必须以“.xml”结尾。
  • 但这不是指文件“test/fixtures/empty.xml”,它确实以“.xml”结尾吗?那么这不应该是有效的吗?
【解决方案2】:

检查字符串 xml_file 以查看它包含的内容。您是否将上传者与其关联?

【讨论】:

  • 到目前为止,我只是将一个空的 xml 文件复制粘贴到了 fixtures 目录中。我已经设置了迁移和模型文件。就是这样。还没有控制器代码或与之相关的任何东西(也没有相关的上传器)。如何在测试环境中检查 string xml_file?
  • 或者我想这一定是问题所在,它尚未将其转换为字符串,并且模型不知道如何处理“上传”文件。
猜你喜欢
  • 1970-01-01
  • 2017-03-29
  • 2019-12-26
  • 1970-01-01
  • 1970-01-01
  • 2017-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多