View spec failing because the ApplicationController method, logged_in?, wants a user to be returned.
Not sure how to spec this. Currently in before(:each) I have:
controller.stub!(:logged_in?).and_return(FactoryGirl.create(:active_user))
#ballots = FactoryGirl.create_list(:full_ballot, 2)
which isn't working:
Failure/Error: render
ActionView::Template::Error:
undefined method 'logged_in?' for #<#<Class:0x007f9c908e4b10>:0x007f9c90873b68>
FWIW: :active_user is the user factory for the user that is attached to the :full_ballot
Update: As requested:
class ApplicationController < ActionController::Base
...
def current_user
#current_user ||= User.find(cookies[:id_token]) if cookies[:id_token]
end
def logged_in?
current_user
end
...
end
See how devise test helpers do it. It looks like you can define this method before tests and it should work:
def logged_in?
FactoryGirl.create :active_user
end
Related
I'm learning rails.
I'm build a simple test application, with a simple authentication scheme.
I'm using a user.role field to group the users.
In my Application Helper i have:
module ApplicationHelper
def current_user
if session[:user_id]
#current_user ||= User.find(session[:user_id])
else
#current_user = nil
end
end
def user_identity
current_user.role if current_user
end
end
Now, in my app, i can use current_user in all controllers as expected, but instead user_identity is not visible.
why?
The application_helper is used mainly to access methods in views - I don't believe it's available in a controller.
The reason your 'current_user' method appears to work is that I'm assuming you're using Devise - when you call 'current_user' it is using the Engine's method rather than your own.
To solve this, write out a new module:
module MyHelper
def current_user
if session[:user_id]
#current_user ||= User.find(session[:user_id])
else
#current_user = nil
end
end
def user_identity
current_user.role if current_user
end
end
And in the controller you're using:
class MyController < ApplicationController
include MyHelper
bla bla bla...
end
Any methods defined in MyHelper will now be available in MyController, as we've included the module in the controller
Helper modules are mixed into the view context (the implicit self in your views) - not controllers.
So you can call it from the controller with:
class ThingsController < ApplicationController
# ...
def index
view_context.user_identity
end
end
Or you can include the helper with the helper method:
class ThingsController < ApplicationController
helper :my_helper
def index
user_identity
end
end
But if you're writing a set of authentication methods I wouldn't use a helper in the first place. Helpers are supposed to be aids for the view.
Instead I would create a concern (also a module) and include it in ApplicationController:
# app/controllers/concerns/authenticable.rb
module Authenticable
extend ActiveSupport::Concern
def current_user
#current_user ||= session[:user_id] ? User.find(session[:user_id]) : nil
end
def user_identity
current_user.try(:role)
end
end
class ApplicationController < ActionController::Base
include Authenticable
end
Since the view can access any of the controllers methods this adds the methods to both contexts.
i'm a beginner in ruby on rails(and english :)), and i'm trying to use functional test but i had an error at fist
1)Error:
test_should_get_new(MicropostControllerTest)
NoMethodError: undefined method 'microposts' for nil:NilClass
My micropost_controller_test.rb
require 'test_helper'
class MicropostControllerTest < ActionController::TestCase
test "should get new" do
get :new
assert_response :success
end
end
My micropost_controller.rb
class MicropostController < ApplicationController
def new
#post = Micropost.new
#posts = current_user.microposts.all
end
def create
#post = current_user.microposts.create(:content => params[:content])
logger.debug "New post: #{#post.attributes.inspect}"
logger.debug "Post should be valid: #{#post.valid?}"
if #post
redirect_to micropost_new_path
else
end
end
end
I tried to put something in microposts.yml but it didn't work.
So, where i can find microposts method for functional test and how do i fix that?? Please help me?
p/s: My app still work in localhost
If you are using Devise for user authentication then you need to authenticate and set current_user in your MicropostController, by for instance having a before_action as follows:
class MicropostController < ApplicationController
before_action :authenticate_user!
def new
#post = Micropost.new
#posts = current_user.microposts.all
end
# rest of the code
end
In your test you need to import devise test helpers as follows, if you haven't done it in your test_helper
class MicropostControllerTest < ActionController::TestCase
include Devise::TestHelpers
end
You can then use the sign_in method to sign in a user using Fixtures in your test. search for some tutorials on that or check the response here to get some clue: Functional testing with Rails and Devise. What to put in my fixtures?
I'm attempting to build a Rails Gem somewhere between Devise and CanCan. Not nearly as complex as Devise, but having views and a controller.
I've created a method to be added to the top of any controller of the parent app that needs it almost exactly like Devise's before_action :authenticate_user! and CanCan's load_and_authorize_resource
I need the method to redirect_to a path in my mounted routes if the requirements are not met.
module MyEngine
module ControllerAdditions
extend ActiveSupport::Concern
module ClassMethods
def pin_verified
current_user ||= nil
#pinned = current_user.nil? ? nil : current_user
redirect_to setup_mobiles_path unless #pinned && #pinned.verified?
end
end
end
end
and in my spec/dummy/app/controllers/users_controller.rb
class UsersController < ApplicationController
pin_verified
def index
#users = User.all
end
end
pin_verified is getting called as it's supposed to but I get the following error:
undefined local variable or method `setup_mobiles_path' for UsersController:Class
Any thoughts on how I should be doing this?
==== edit ====
I altered this now to raise a custom exception, but now I need to rescue that exception some how and redirect to the needed path.
def pin_verified
current_user ||= nil
#pinned = current_user.nil? ? nil : current_user
unless #pinned && #pinned.verified?
raise ValidatedPinExpired
end
end
I tried adding this to the ApplicationController of my gem, but it doesn't seem to be hitting Controller at all.
module MyEngine
class ApplicationController < ActionController::Base
rescue_from Exception do |exception|
Rails.logger.info "==== exception: #{exception} ===="
redirect_to setup_mobiles_path
end
end
end
I have defined a helper method as such (for my rails engine):
module Xaaron
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
helper_method :current_user
helper_method :authenticate_user!
def current_user
#current_user ||= Xaaron::User.find_by_auth_token(cookies[:auth_token]) if cookies[:auth_token]
end
def authenticate_user!
if current_user
true
else
redirect_to xaaron.login_path
false
end
end
protected
def record_not_found
flash[:error] = 'Could not find specified role'
redirect_to xaaron.record_not_found_path
true
end
end
end
As far as I know everything above is correct in terms of creating helper methods. So now I need to use this helper method:
module Xaaron
class ApiKeysController < ActionController::Base
before_action :authenticate_user!
def index
#api_key = Xaaron::ApiKey.where(:user_id => current_user.id)
end
def create
#api_key = Xaaron::ApiKey.new(:user_id => current_user.id, :api_key => SecureRandom.hex(16))
create_api_key(#api_key)
end
def destroy
Xaaron::ApiKey.find(params[:id]).destroy
flash[:notice] = 'Api Key has been deleted.'
redirect_to xarron.api_keys_path
end
end
end
As you can see, before every action the user must be authenticated. So the authenticat_user!
method is then called.
Lets write a test for this
it "should not create an api key for those not logged in" do
post :create
expect(response).to redirect_to xaaron.login_path
end
This, we expect, to send us back to the login path because we are not signed in, and as you will recall we are using authenticate before every action in the API Controller. What do we get instead:
1) Xaaron::ApiKeysController#create should not create an api key for those not logged in
Failure/Error: post :create
NoMethodError:
undefined method `authenticate_user!' for #<Xaaron::ApiKeysController:0x007f898e908a98>
# ./spec/controllers/api_keys_controller_spec.rb:9:in `block (3 levels) in <top (required)>'
Last I checked the way I defined a helper method is how rails casts has done it, how other stack questions have done it and how rails docs states to do it - unless I missed some majour step - why isn't this working?
Maybe I haven't seen a helper method set up like this before (I'm new to rails) but the helper methods I've seen are defined without controllers.
Usually I see a file like this in the helpers folder
module SessionsHelper
def sign_in(user)
remember_token = User.new_remember_token
cookies.permanent[:remember_token] = remember_token
user.update_attribute(:remember_token, User.encrypt(remember_token))
self.current_user = user
end
def current_user=(user)
#current_user = user
end
...
and then
include SessionsHelper
In the application controller.
To me it looks like you're calling the controller a helper method, I'm not sure what the benefits of that would be - but I suppose I wouldn't.
Sorry if this wasn't helpful
I'm doing an authentication application. I have this code
class UsersController < ApplicationController
def new
#user = User.new
#title = "User Sign Up"
end
def create
#user = User.new(params[:user])
sign_in_check #user
if #user.save
#flash[:status] = true
#flash[:alert] = "You have successfully signed up!!"
#sign_in_check #user
redirect_to root_path, :flash => { :success => "Welcome to the Bakeshop"}
else
#title = "User Sign Up"
render 'new'
end
end
end
This is a simple sign-up code, and whenever I try and sign up, rails returns an error:
undefined method `sign_in_check' for #<UsersController:0x68c0a90>
but I defined a method sign_in_check in my Users_helper.rb:
module UsersHelper
def sign_in_check(user)
#some stuff to enable session
end
end
Does anyone have an idea why this is happening, and how to fix it?
The reason is your method is a helper. Helpers will be available in views with matching name by default, but not open to controllers without setting.
Two ways to fix:
Allow this helper in UsersController
class UsersController < ApplicationController
helper :user #This will expose UsersHelper module to UsersController
Instead, put this method into ApplicationController. I would prefer this due to the method's nature.
Include your UserHelper in your UserController as follows and you should be able to use any methods defined within the helper.
class UsersController < ApplicationController
include UsersHelper
...
end
This is usually put in the application controller
class ApplicationController < ActionController::Base
def sign_in_check(user)
#some stuff to enable session
end
end
Helpers are used for views. If you want to use it in both - you can do that, but that doesn't sound like what you're looking for here.
just include your helper module in your controller
class UsersController < ApplicationController
helper :user
...
end
Thanks