【问题标题】:RSpec test doesn't work but it's works great in browserRSpec 测试不起作用,但在浏览器中效果很好
【发布时间】:2012-10-17 20:46:20
【问题描述】:

我不知道我做错了什么,所以请帮帮我。

正如标题所说,一切都在浏览器中运行良好。所以我想这是我无法正确使用的规范。

我已经多次重写了我的助手、控制器和规范中的代码。

这是我现在的规格:

describe "visit as admin" do
    before do
      sign_in admin
      visit organization_users_path # row 20 of users_controller_spec
    end
    it "should display right page" do
      page.should have_selector('title', text: "Users") 
    end
  end

当我运行它时,我得到:

1) Organization::UsersController visit as admin should display right page
     Failure/Error: visit organization_users_path
     NoMethodError:
       undefined method `users' for nil:NilClass
     # ./app/controllers/organization/users_controller.rb:5:in `index'
     # ./spec/controllers/organization/users_controller_spec.rb:20:in `block (3 levels) in <top (required)>'

这是我的控制器和助手:

# helper
def current_organization
  @current_organization ||= current_user.organization
end

def admin_user
  unless current_user.admin?
    redirect_to root_path
  end
end

#controller
class Organization::UsersController < ApplicationController
  before_filter :admin_user

  def index
    @users = current_organization.users
  end
end

编辑1:来自rake routes

organization_users GET    /organization/users(.:format)          organization/users#index

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rspec rspec-rails


    【解决方案1】:

    似乎在控制器的index 函数中:current_organizationnil

    请确保这个助手返回一个有效的对象:

    def current_organization
      @current_organization ||= current_user.organization
      raise @current_organization.inspect # <--- use this to inspect this value and delete afterwards
    end
    

    【讨论】:

    • 这个引导我走向正确的方向。我没有在我的规范中创建任何组织,因为我认为我不需要这样做。我只是想检查一下标题;)所以当我创建组织时,一切都很好。该页面在没有分配给一个用户的情况下工作,所以我认为我不需要分配用户。感谢您的帮助。
    【解决方案2】:

    错误告诉您current_organisation 为 nil,这似乎合乎逻辑,因为它是通过 current_user 加载的,而 current_user 在您的上下文中为 nil。

    您可以查看https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara 以让用户登录测试。

    但不要忘记在您的设置中记录一个作为组织的用户,这样 current_organization 助手就不会返回 nil

    编辑:我猜您正在使用 devise 进行登录,如果不是这种情况,请告诉我们您使用什么进行身份验证

    【讨论】:

    • 不使用任何特定的 gem 进行身份验证。
    • 在这种情况下,您可以简单地存根 current_user 帮助器以返回用户而不是 nil
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多