Good day!
I have a Rails app with a controller that sets an instance variable in a
before_filter, like this:
class PostsController < ApplicationController
before_filter :set_site_language
def set_site_language
@site_language = cookie[‘lang’] ?
Language.find_by_code(cookie[‘lang’]) :
Language.find(:first)
end
def index
@posts = Post.find_by_language_id(@site_language.id)
end
end
The controller has the following spec:
describe PostsController do
it “should show home page” do
get :index
response.should be_success
end
end
And the equivalent test:
class PostsControllerTest < ActionController::TestCase
def test_should_show_home_page
get :index
assert_response :success
end
end
The test runs fine, but the spec fails with the following error on line
with @posts = Post.find_by_language_id(@site_language.id)
:
RuntimeError in ‘PostsController should show home page’
Called id for nil, which would mistakenly be 4 – if you really wanted
the id of nil, use object_id
Seems that @site_language does not get assigned when spec runs. Could
you please help me solve this problem?
Yours,
Damian
On Jul 3, 2008, at 2:24 AM, Damian T. wrote:
def set_site_language
@site_language = cookie[‘lang’] ?
Language.find_by_code(cookie[‘lang’]) :
Language.find(:first)
Shouldn’t this be cookies, not cookie? Doesn’t explain why the test
passes when the example fails, but it seems that both should be
raising errors on this.
David C. wrote:
On Jul 3, 2008, at 2:24 AM, Damian T. wrote:
def set_site_language
@site_language = cookie[‘lang’] ?
Language.find_by_code(cookie[‘lang’]) :
Language.find(:first)
Shouldn’t this be cookies, not cookie? Doesn’t explain why the test
passes when the example fails, but it seems that both should be
raising errors on this.
Yes, there should be cookies
, but the problem still exists.
I believe the problem is that you’re not telling the Language model
what to stub/mock when it calls the find method inside of
set_site_language.
I’m not entirely sure, but I would imagine that the TestUnit test is
passing, because it’s using the full Rails stack to run the test.
Try doing something like this (code below):
On Jul 3, 2008, at 2:24 AM, Damian T. wrote:
def set_site_language
The controller has the following spec:
describe PostsController do
before(:each) do
@language_mock = mock_model(Language)
controller.stub!(:set_site_language).and_return @language_mock
end
Bryan R. wrote:
I believe the problem is that you’re not telling the Language model
what to stub/mock when it calls the find method inside of
set_site_language.
I’m not entirely sure, but I would imagine that the TestUnit test is
passing, because it’s using the full Rails stack to run the test.
Try doing something like this (code below):
Thanks for your help!
Anyway, switching to Test::Spec has solved the problem.