我使用public_activity gem在我的应用程序中生成活动提要,在我的模型中,我使用devise的current_user来识别活动的所有者。
class Question < ActiveRecord::Base
...
include PublicActivity::Model
tracked owner: ->(controller, model) { controller.current_user }
...
end我意识到在模型中引用current_user不是标准,但这是他们建议你这么做的方式。
这在应用程序中运行得很好,但是我在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方法在测试中工作?
发布于 2014-02-27 20:35:04
就我个人而言,我认为您不应该从controller内部引用model。因为您不希望每次访问controller对象时都实例化model对象。
例如,您可能希望从后台工作人员访问model:谁是您的current_user,您的controller是什么?
这同样适用于您的测试套件。你想测试你的model,而不是你的controller。
而且,您可能并不总是希望跟踪活动。
更好的方法是从current_user传递controller对象。Ryan在他的铁路公共活动中有一个很好的例子(参见“排除行动”):
class Question < ActiveRecord::Base
include PublicActivity::Common
end对于你想要追踪的每一个活动
@question.create_activity :create, owner: current_user发布于 2014-02-27 18:22:05
您需要在RSpec中添加spec/support/devise.rb助手
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
end你可以找到更多的信息这里
https://stackoverflow.com/questions/22076699
复制相似问题