Can anyone help me by explaining why this test fails?
An article has a title and a url (among other things). If we don’t get
a title from the create article form, then i use hpricot and open-uri to
look on the net and generate the title from the web page’s title. In
the context of my app, it works fine (although the code is quite clumsy,
i’m still a noob coder). However, a simple test that the article has a
title is failing - in the tests, the constructor doesn’t seem to be
doing its job properly.
here’s the test:
#article should generate a title from a url if not given a title
def test_makes_a_title_from_url
article_hash = {:url => “www.google.co.uk”}
article = Article.new(:article => article_hash, :user => 1)
assert_equal(“iGoogle”, article.title)
end
The test is failing because title is equal to nil. (normally i would
just assert_not_nil, but i used assert_equals here because i wanted the
test to output what title was equal to, in case it was some broken
string or something)
Here’s the constructor:
##################################################################
#constructor - takes the data from the article form (the
#article/new view page), as a hash called :article, and the
#current user, as :user
##################################################################
#params:
- :article - a hash containing :url, :title, :tags
- :user - a user, usually the current user (the person creating
#the article)
##################################################################
def initialize(params = {})
super(params[:article])
#first, check that the url is a valid web page
begin
web_page = open(self.url)
rescue #look for any exceptions
#if it failed to validate the url, delete the object and return
self.destroy
return
end
#autogenerate the title from the web page’s title element if a
#title is not given
if self.title == “”
self.title = ((Hpricot(web_page))/“title”).first.inner_html
end
#set some other values
self.added_at = DateTime.now.to_s
self.points = 0
self.user_id = params[:user]
self.save
#mark as scored up by the user who added it
self.change_score :user_id => self.user_id, :points => 1
return true
end
I thought it might be to do with hpricot/open-uri so i required them at
the top of the test. But that hasn’t helped - i don’t even know if
that’s the proper way to handle requires in testing. (Will the tests
automatically use the requires and includes in my environment.rb? I
don’t have anything in environment/test.rb besides the default stuff
rails puts in there.)
This is probably something dumb, and obvious to most - can anyone see
what i’m doing wrong?