Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to use Regular Expression in RSpec have_selector line

I'm brand new to Ruby/Rails/RSpec, and hopefully this is a dumb/simple question. I'm currently working on writing RSpec tests for our current projet. What I am am currently doing involves writing a test for displaying a last login time/date on a page.

What I want to do is just test if the date/time is present in the format we want. I'm using a regular expression to check for the formatting. I'm creating the regexp, then trying to use the should have_selector line like so (please excuse the ugly regexp)-

it "should display last login date and time" do
  date_time_regex = /Last Login: [0-9][0-9]-[0-9][0-9]-[0-9][0-9], [0-9][0-9]:[0-9[0-9]]/
  visit root_path
  response.should have_selector("date_time", :content => date_time_regex)
end

When I try run the test I get the following error-

1) LayoutLinks when signed in should display last login date and time
 Failure/Error: response.should have_selector("date_time", :content => date_time_regex)
 NoMethodError:
   undefined method `include?' for #<Regexp:0xef2a40>
 # ./layout_links_spec.rb:60:in `block (3 levels) in <top (required)>'

So it looks like I can't pass in a regexp, but I'm not sure what to do next? Thanks in advance for any help!

like image 974
Will Avatar asked May 25 '11 15:05

Will


2 Answers

date_time_regex = /Last Login: [0-9][0-9]-[0-9][0-9]-[0-9][0-9], [0-9][0-9]:[0-9[0-9]]/

response.should have_selector('data_time') do |data_time|
  data_time.should contain(date_time_regex)
end

or...

response.should have_selector('data_time') do |data_time|
  data_time.should =~ date_time_regex
end
like image 180
ChuckJHardy Avatar answered Nov 15 '22 05:11

ChuckJHardy


One thing that will help you is that you can do \d instead of [0-9]. So you then get

/Last Login: \d\d-\d\d-\d\d, \d\d:\d\d/

which is a bit more readable.

like image 35
Max Williams Avatar answered Nov 15 '22 04:11

Max Williams