Rails Functional Testing Problem

I'm trying to run some functional tests on Rails. However I am coming up with the following error.

RuntimeError: Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id     app/controllers/posts_controller.rb:11:in `create'     posts_controller_test.rb:5:in `test_should_create'

Here is my test file

require File.dirname(__FILE__) + "/../test_helper"

class PostsControllerTest < ActionController::TestCase def test_should_create   post :create, :post => { :message => 'Sausage and Egg Sandwich'} end end

Here is my controller

class PostsController < ApplicationController   def index     @posts = Post.all(:order => "created_at DESC")     respond_to do |format|       format.html     end   end

  def create     @post = Post.create(:message => params[:post])     @post.user_id = current_user.id     respond_to do |format|       if @post.save         format.html { redirect_to posts_path }         format.js       else         flash[:notice] = "Message failed to save."         format.html { redirect_to posts_path }       end     end   end end

Assuming that it is this line that is causing the error, what is the value of current_user when you run the test?

Colin

Colin Law wrote in post #1055633:

Colin Law wrote in post #1055633:

class PostsController < ApplicationController def index @posts = Post.all(:order => "created_at DESC") respond_to do |format| format.html end end

def create @post = Post.create(:message => params[:post]) @post.user_id = current_user.id

Assuming that it is this line that is causing the error, what is the value of current_user when you run the test?

Colin

Nil. Because I haven't specified it, and the user isn't logged in. I've tried invoking the current_user or writing user_id within the test, but that hasn't worked.

You need to be logged in order to write a post, but I wasn't sure that mattered when writing the test?

Of course it matters, the tests should, for example, check that you cannot do things that you should not be able to do without logging in. How to accomplish this depends on how your authentication is done. Perhaps you need to set something in the session before running the test. Google should show you how to do that.

Colin

Thank you Colin

sherpa derpa wrote in post #1055638:

Thank you Colin

I'm using nifty-authentication for what it's worth

Really struggling attempting to implement this globally.

Any suggestions to those who have used nifty_authentication?

Once again you have not quoted previous messages so anyone finding this would have difficulty following the thread. I don't know about nifty_authentication but for authlogic the logon action actually creates a UserSession, so to logon in the test one does something like     UserSession.create( users(:test_user) )

Colin

Colin Law wrote in post #1055698: