tags:

views:

218

answers:

1

Hello! Just for fun, I wrote a very small rails blog (just a hello world). Now I want to create a post using mechanize. So I created a Ruby Prog and started coding.

Here is my problem: Rails creates my form element including all inputs. In HTML my inputs look like this:

<input type="text" size="30" name="post[title]" id="post_title">

or

<textarea rows="20" name="post[description]" id="post_description" cols="40"></textarea>

Well... Here is my Ruby Prog using Mechanize:

require 'rubygems'
require 'mechanize'

agent = WWW::Mechanize.new

page = agent.get('http://localhost:3000/posts/new')
target_form = page.form_with(:class => 'new_post')
target_form.post[title] = "test"
target_form.post[description] = "test"
page = agent.submit(target_form)
puts "end"

I know where my error is but I don't know how to fix it. At target_form.post[title] = "test" it crashes, cause of

undefined method `name' for nil:NilClass (NoMethodError)

I think (please correct me), it's because of the input name, cause it is post[title] instead of only post right? How can I fix it?

+1  A: 

How about

target_form.field_with(:name => "post[title]").value = "test"
target_form.field_with(:name => "post[description]").value = "test"
anshul
When I try your code, it tells me:undefined method `field_with' for nil:NilClass (NoMethodError)Any ideas?
Newbie
In that case `target_form = page.form_with(:class => 'new_post')` is not working.
anshul
Oh, okay, you are right. I forgot to include my proxy. So I did this.Now I get another error:...mechanize.rb:553:in `fetch_page': 503 => Net::HTTPServiceUnavailable (WWW::Mechanize::ResponseCodeError)Seems like mechanice is not able to access my page, right? Any ideas why?This seems to be, cause of localhost. Using another domain like google.com or something will work.
Newbie
Could be a number of things but the first thing I would check for is a time out. Try increasing mechanize's timeout.
anshul