Search code examples
ruby-on-railsrubyruby-on-rails-3rspecrspec-rails

RSpec test doesn't work but it's works great in browser


I don't know what I'm doing wrong so please help me out.

So as the title says all works great in the browser. So I guess it's the spec I'm not able to get right.

I've rewrote code in my helpers, controllers and spec several times to.

Here's my spec for now:

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

When i run it i get:

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)>'

And heres my controller and helper:

# 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

Edit 1: From rake routes:

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

Solution

  • Seems like in the index function for the controller: current_organization is nil.

    Please make sure this helper is returning a valid object:

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