Rspec模型测试 - 模型中的current_user

时间:2014-02-27 18:04:16

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

我正在使用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方法在我的测试中工作?

2 个答案:

答案 0 :(得分:3)

我个人认为你不应该在controller内引用model。因为您不希望每次要访问controller时都实例化model对象。

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

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

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

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

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

对于您想要跟踪的每项活动

@question.create_activity :create, owner: current_user

答案 1 :(得分:0)

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

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

您可以找到更多信息here

相关问题