testing - 具有设计身份验证的 rspec Controller 测试

标签 testing authentication rspec controller

我在使用 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 the sign_in and sign_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/

相关文章:

python - 如何跨 pytest 装置同步参数化?

git - 使用 Capistrano 部署 Zend Framework 站点时遇到问题 : SSH Authentication error

php - 登录时重定向

ruby - 如何测试使用 rspec 的 block 的函数

ruby-on-rails - rspec capybara 测试仅在 chrome 中显示 "data:,"然后因 EOFError 而失败

user-interface - 代码部署后如何比较网站的用户界面元素?

testing - 测试Vue.js(^2.5.*)组件时提示prop被突变如何处理

firebase - Flutter Phone认证报错原始例子

ruby-on-rails - RSpec, stub 嵌套资源方法

ruby-on-rails - 密码,Password_Confirmation ActiveModel::MassAssignmentSecurity::Error: