【问题标题】:Rspec model testing - current_user in modelRspec 模型测试 - 模型中的 current_user
【发布时间】:2014-02-27 18:04:15
【问题描述】:

我正在使用 public_activity gem 在我的应用程序中生成活动源,在我的模型中,我正在使用 devise 的 current_user 来识别活动的所有者。

class Question < ActiveRecord::Base
  ...
  include PublicActivity::Model
  tracked owner: ->(controller, model) { controller.current_user }
  ...
end

我意识到在模型中引用 current_user 不是常态,但这就是他们recommend doing it 的方式。

这在应用程序中运行良好,但我的 Rspec 测试遇到了问题,出现以下错误:

Failure/Error: expect(create(:question)).to be_valid
NoMethodError:
undefined method `current_user' for nil:NilClass
# ./app/models/question.rb:8:in `block in <class:Question>'
# ./spec/models/question_spec.rb:7:in `block (3 levels) in <top (required)>'

测试本身是典型的:

describe "Factory" do
  it "has a valid factory" do
    expect(create(:question)).to be_valid
  end
end

这是我的工厂:

FactoryGirl.define do
  factory :question do
    title { Faker::Lorem.characters(30) }
    body { Faker::Lorem.characters(150) }
    user_id { 1 }
    tag_list { "test, respec" }
  end
end

如何让我的模型中的这个 current_user 方法在我的测试中工作?

【问题讨论】:

    标签: ruby-on-rails rspec devise public-activity


    【解决方案1】:

    我个人认为您不应该在model 中引用controller。因为您不想每次访问model 时都实例化controller 对象。

    例如,您可能想从后台工作人员访问model:谁是您的current_user,您的controller 是什么?

    这同样适用于您的测试套件。你想测试你的model,而不是你的controller

    此外,您可能并不总是想跟踪活动。

    更好的方法是从controller 传入current_user 对象。 Ryan Bates 在他的Railscast on Public Activity 中有一个很好的例子(参见“排除操作”):

    class Question < ActiveRecord::Base
      include PublicActivity::Common
    end
    

    对于您要跟踪的每项活动

    @question.create_activity :create, owner: current_user
    

    【讨论】:

    • 我试图避免将 create_activity 放在每个方法中,但你是对的 - 这是要走的路。感谢您的帮助。
    【解决方案2】:

    您需要在spec/support/devise.rb 中添加 RSpec 助手:

    RSpec.configure do |config|
      config.include Devise::TestHelpers, :type => :controller
    end
    

    您可以找到更多信息here

    【讨论】:

    • 感谢您的回复!我在 spec/support/devise.rb 中有这个,并且 current_user 在控制器中工作正常。这只是我得到这个错误的模型测试。
    • 我的错。虽然看起来问题是controller 为零,而不是缺少current_user
    猜你喜欢
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多