gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:35:59 24 4
gpt4 key购买 nike

如果我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com