aross
aross

Reputation: 5789

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

Upvotes: 1

Views: 541

Answers (2)

pjam
pjam

Reputation: 6356

The error tells you that the current_organisation is nil, and that seems logical as it's loaded through the current_user which is nil in your context.

You can take a look at https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara to log a user in the tests.

But don't forget to log a user which as an organization in your setup so the current_organization helper doesn't return nil

EDIT : I'm guessing you're using devise for login, if this is not the case, please let us know, what you're using for authentication

Upvotes: 0

Stoic
Stoic

Reputation: 10754

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

Upvotes: 1

Related Questions