I am using watir for testing my rails 3 webapplication which is working fine.

My problem is, my current page url is localhot:3000/sites/535/ecosystem/new. NOw:

  • I want to logout from the page and re-login.
  • Then, I will reach at dashboard page, where I am displaying list of sites.
  • I want to click on the last created site name, so that, I redirects me back to same state, where I left that study i.e. localhost:3000/sites/535/ecosystem/new

But my problem is I am using datatable for displaying sites, and it is sorting site list with sitename.

One solution I got for this problem is, If I can fetch @id = params[:id] from localhost:3000/sites/535/ecosystem/new then I can do:

@browser.goto "localhost:3000/sites/#{@id}"

which is the url for my site link in dashboard page.

HOW TO FETCH params[:id] from current URL in watir or watir-webdriver?

thanks

有帮助吗?

解决方案

I have resolved this problem with ruby logic, but still waiting for some good logic.

Solution

url = @browser.url
#> ["localhost:3000/sites/535/ecosystem/new"]

uri = url.split("/sites/")
#> ["localhost:3000", "535/ecosystem/new"]

uri = uri[1].split("/ecosystem/new")[0]
#> "535"

I can now access id i.e 535 in current url. But still wating for some good logic for resolving this issue.

Thanks

其他提示

No, you cannot use Rails helpers there as params[:id] because it does not make sense to Watir.

However, there are two possible ways to solve this problem.

First possible way is to parse the URL similarly like you did:

@browser.url.scan(%r{/(\d+)/}).flatten[0] # => "535"

Another way would be to use Rails models themselves. Let's say you know the name of the site you're looking for (if you don't then how did you end up at the url itself?) then you can get it from the database directly:

Site.where(name: "my site").first.id # => "535"

You can also use Rails url helpers by including them into your test code (untested code):

include Rails.application.routes.url_helpers
@browser.goto new_site_url

In that way you don't have to hardcode the urls into your tests.

Use RegEx

Not sure if this is sufficiently "good logic" for you, but it's another way that's more direct, regardless.

Use RegEx on the the URL to capture the id value in between sites/ and /ecosystem:

@browser.url.match( /(?!sites\/)([0-9]*)(?=\/ecosystem)/ ).captures.first
#=> "535"

If you're not familiar with RegEx then this looks more complicated than it actually is. It essentially just finds sites/ and /ecosystem and then "captures" any number of digits (between 0 and 9) in between.

You can visually play with the RegEx pattern here: https://regexr.com/5q1eg

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top