我最近开始了 rspec 编码,而且我是 Rails 框架的新手,当我在 Controller 中使用“current_user”时,rspec 失败了。请检查下面我的 Controller 和 rspec 代码。提前致谢。
Controller 代码:
def task
@tasks = current_user.alerts.where(kind: "TASK")
end
rspec代码:
describe "get #task" do
it "assigns a task" do
sign_in(@user)
get :task
expect(response).to have_http_status(200)
end
最佳答案
你可以这样做:
@request.env["devise.mapping"] = Devise.mappings[:user]
user = FactoryGirl.create(:user) # Don't forget to create a factory for user
user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
sign_in user
最好把它放在support/devise.rb中:
module ControllerMacros
def login_user
before(:each) do
@request.env["devise.mapping"] = Devise.mappings[:user]
user = FactoryGirl.create(:user)
user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
sign_in user
end
end
end
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
config.extend ControllerMacros, :type => :controller
end
你可以说login_user而不是sign_in(@user)
关于ruby-on-rails - rspec 失败, Controller 中写入的代码为 'current_user',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27406153/