如果我有一个Desive model用户,其中只有那些角色为:admin的用户才允许查看某个url,我如何编写RSpec集成测试来判断该url的状态是否返回200?

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

这个问题的答案是假的:Stubbing authentication in request spec,但我一辈子都无法让它与Desive一起工作.CanCan在判断能力时接收到一个nil用户,当然,该能力没有正确的权限.

集成规范中没有对控制器的访问权限,所以我不能对当前的用户进行存根,但我想这样做.

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

NOTE!!!:自从提出这个问题以来,所有这些都发生了变化.目前最好的方法是:http://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara

推荐答案

@普赛格的回答越过了我的底线.为了完整性,我这样做可以轻松设置请求规范和控制器规范(使用FactoryGirl创建用户实例):

in/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

同样,在控制器规范中使用"signed_in_as_valid_user"(它包装了designe::TestHelpers与FactoryGirl的用户sign_in方法)

Ruby-on-rails相关问答推荐

如何使用继承类 (STI) 获取 Ruby on Rails 类中基类的实例

如何在 Rails 中注释掉 ERB?

你如何发布到 Capybara 中的 URL?

为特定操作使用布局

有没有一种简单的方法可以让 pow 为 https 服务?

ArgumentError:您需要使用 :if 提供至少一个验证

骨干model.destroy()即使工作正常也会调用错误回调函数?

Rails 3 中图像路径的完整 url

从 Authlogic 迁移到 Devise

如何从 ActiveRecord 中的每个组中获取最新记录?

如何在 rspec 测试中输出变量?

Rails - 如何在 f.submit 上放置确认弹出窗口?

Rails:使用 link_to 创建不带 href 的链接

对象不支持此属性或方法 Rails Windows 64bit

Rails 中是否有 HTML 安全截断方法?

Ruby on Rails i18n - 想要在模型中翻译自定义消息

快速添加链接[:notice]

从 Rails 控制器获取主机名

Ruby 1.87 与 1.92 Date.parse

在 El Capitan 上安装 Nokogiri (1.6.7) 时出错