我在使用 rspec 测试 Controller 和设计身份验证时遇到问题。
我有以下设置
我已经包含了
config.include Devise::TestHelpers, :type => :controller
在我的 spec_helper.rb 中
在我的 merchants_controller_spec.rb 中
describe MerchantsController do
before :each do
@user = Factory(:user)
@merchant = Factory(:merchant, :user_id => @user.id,:is_approved => false, :is_blacklisted => false)
controller.stub!(:current_user).and_return(@user)
end
describe "GET index" do
it "assigns all merchants as @merchants" do
merchant = Factory(:merchant,:is_approved => true, :is_blacklisted => false)
get :index
assigns(:merchants).should eq([merchant])
end
end
end
我的 merchants_controller.rb
class MerchantsController < ApplicationController
before_filter :authenticate_user!
def index
@merchants = Merchant.approved
debugger
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @merchants }
end
end
end
我有一个在商家模型中批准的范围
scope :approved, where(:is_approved => true, :is_blacklisted => false)
现在我的问题是,即使我 stub current_user 并将@user 作为 current_user 返回,我的 merchants_controller 索引规范失败。但是如果我注释掉 authenticate_user!然后规范通过,
没有 authenticate_user!索引操作的调试器被捕获但使用 authenticate_user!调试器未被捕获。
我认为替换 current_user 有问题,我无法弄清楚。
帮帮我..
最佳答案
您是否阅读了 github 上的文档? ?:
Devise includes some tests helpers for functional specs. To use them, you just need to include
Devise::TestHelpers
in your test class and use thesign_in
andsign_out
methods. Such methods have the same signature as in controllers:
sign_in :user, @user # sign_in(scope, resource)
sign_in @user # sign_in(resource)
sign_out :user # sign_out(scope)
sign_out @user # sign_out(resource)
关于testing - 具有设计身份验证的 rspec Controller 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7452295/