ruby-on-rails - 如何使用 RSpec 和 Devise/CanCan 进行集成测试?

标签 ruby-on-rails rspec devise cancan

如果我有一个 Devise 模型用户,其中只有具有 :admin 角色的用户才可以查看某个 url,我如何编写 RSpec 集成测试来检查该 url 的状态是否返回 200?

def login(user)
  post user_session_path, :email => user.email, :password => 'password'
end

这是在这个问题的答案中伪建议的:Stubbing authentication in request spec ,但我一生都无法让它与 devise 一起工作。 CanCan 在检查能力时收到一个 nil User,这自然没有正确的权限。

集成规范中无法访问 Controller ,因此我无法 stub current_user,但我想做这样的事情。

describe "GET /users" do
  it "should be able to get" do
    clear_users_and_add_admin #does what it says...
    login(admin)
    get users_path
    response.status.should be(200)
  end
end

注意!!!:自从提出问题以来,这一切都发生了变化。目前最好的方法是在这里:http://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara

最佳答案

@pschuegr 自己的回答让我越线了。为了完整起见,我所做的可以让我轻松设置请求规范和 Controller 规范(使用 FactoryGirl 创建用户实例):

在/spec/support/sign_in_support.rb中:

#module for helping controller specs
module ValidUserHelper
  def signed_in_as_a_valid_user
    @user ||= FactoryGirl.create :user
    sign_in @user # method from devise:TestHelpers
  end
end

# module for helping request specs
module ValidUserRequestHelper

  # for use in request specs
  def sign_in_as_a_valid_user
    @user ||= FactoryGirl.create :user
    post_via_redirect user_session_path, 'user[email]' => @user.email, 'user[password]' => @user.password
  end
end

RSpec.configure do |config|
  config.include ValidUserHelper, :type => :controller
  config.include ValidUserRequestHelper, :type => :request
end

然后在请求规范中:

describe "GET /things" do
  it "test access to things, works with a signed in user" do
    sign_in_as_a_valid_user
    get things_path
    response.status.should be(200)
  end
end

describe "GET /things" do
  it "test access to things, does not work without a signed in user" do
    get things_path
    response.status.should be(302) # redirect to sign in page
  end
end

同样,在 Controller 规范中使用“signed_in_as_valid_user”(它使用来自 FactoryGirl 的用户包装 Devise::TestHelpers Sign_in 方法)

关于ruby-on-rails - 如何使用 RSpec 和 Devise/CanCan 进行集成测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5865555/

相关文章:

javascript - rails 4 : Passing a variable from controller to javascript

javascript - (Ruby、Rails、Javascript)使用 javascript 窗口等管理嵌套模型...?

ruby-on-rails - ActiveRecord Relation where method matching on unique id returns object slightly diff then when traversing the array and matching on the same id

ruby-on-rails - Rails 教程 : undefined local variable or method `static_pages_index_path' 中的 rspec 错误

ruby-on-rails - 在 Ruby on Rails 中为 Rspec 和 Rack::Test 设置请求 header

ruby-on-rails - "reload!"在 Rails 控制台中似乎并不总是有效的原因是什么?

ruby-on-rails - 在记录更新时访问关联的先前值

ruby - 有没有办法在 RSpec 中取消 stub ?

ruby-on-rails - 使用 Devise 和 OmniAuth-SAML 在 Rails 中设置 SAML 回调

ruby-on-rails - Rails、Node.js 跨服务器认证