【问题标题】:I want to use on seeds a method that I use for tests on RSpec我想在种子上使用一种用于 RSpec 测试的方法
【发布时间】:2018-09-01 01:26:56
【问题描述】:

我有这个 AuthorizationHelpers,我正在 RSpec 上使用。

module AuthorizationHelpers
  def assign_role!(user, role, post)
    Role.where(user: user, post: post).delete_all
    Role.create!(user: user, role: role, post: post)
  end
end

RSpec.configure do |c|
  c.include AuthorizationHelpers
end

现在我想在种子上使用这种方法assign_role!。 像这样:

Post.all.each do |post|
    [:manager, :editor, :viewer].each do |role|
      User.all.where(admin: false).each do |user|
          assign_role!(user, role, post)
      end
    end
  end

如果我尝试在 Rails 控制台上使用它,我会收到错误:

NoMethodError: undefined method `assign_role!' for main:Object

有什么方法可以在种子上使用它吗?还是我需要做其他事情?

【问题讨论】:

  • 当你调用assign_role!时,你想象你调用的是什么对象assign_role!on
  • 此assign_role 用于为帖子中的用户添加角色。
  • 问题不在于目的是什么。问题是你打算调用什么object?通常,当您调用某个东西时,它看起来像 Class.methodModule.method@object.method。但是,当您调用裸露的assign_role!(未调用ClassModule@object)时,您认为会发生什么。你认为这是在调用什么对象? (提示:检查您发布的错误。)
  • 这是给用户的。我想把它放在一个帮手上。

标签: ruby-on-rails ruby-on-rails-4 sqlite rspec-rails seeding


【解决方案1】:

最后,OP放弃使用模块,在seeds.rb做了如下操作:

unless Post.exists?(title: title)
post = Post.create!(...)
[:manager, :editor, :viewer].each do |role|
  if user = User.find_by_email("#{role}@newscity.com")
    user.roles.create(post: post, role: role)
  end
end

查看聊天(在原始问题 cmets 中)了解整个故事。

【讨论】:

    【解决方案2】:

    此答案不一定与您的问题有关,而更多地与您的代码的语义有关。

    首先:为什么不将assign_role! 定义为用户模型的实例方法并且可以在任何地方使用?似乎是该逻辑存在的合理位置。

    第二:种子应该是您的应用程序在全新安装后正常工作的最少数据。通常是一次性命令;要在规范中创建数据,请考虑改用工厂(一个流行的库是 FactoryGirl)。

    您的代码调用spec 文件夹中定义的内容感觉不自然。

    【讨论】:

    • 您好,谢谢您的回复。我已经在使用 FactoryGirl。我会试试你说的。
    猜你喜欢
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多