Search code examples
regexcucumberwatir

Cucumber::ArityMismatchError


I have these .feature statements:

I am logged in as an "Teacher".
I am logged in as an "Professor".
I am logged in as an "Student".
I am logged in as a "NoRole"

for which I wrote a regex

I (\w{2})?\s?(log|login|logged)\s?(\w{2}) as (an|a) "(Teacher|Professor|Student|NoRole)"\.?

I had put them in quotes so that I can run a case block on them like this:

case role_type
     when 'Student'
       on(LoginPage).login_with(FigNewton.Studnet_email,'password')
and so on ... for other roles

Now when I run this regex in step definitions with Given

Given(/^I (\w{2})?\s?(log|login|logged)\s?(\w{2}) as (an|a) "(Teacher|Professor|Student|NoRole)"\.?$/) do |user_role|
  # code
end

it gives this error:

Cucumber::ArityMismatchError: Your block takes 1 argument, but the Regexp matched 5 arguments

Query: As far as I know, arguments are those in between quotes like "Professor" so which five arguments it is talking about.

On this Cucumber::ArityMismatchError error after Transform I found that there shouldn't be any block, but my regex wont work if there are no blocks, So how to separated role type from regex arguments(blocks)


Solution

  • As the error message says, the step definition is expecting one argument - user_role. However, you are capturing 5 groups, which means you are passing 5 arguments:

    • (\w{2})
    • (log|login|logged)
    • (\w{2})
    • (an|a)
    • (Teacher|Professor|Student|NoRole)

    Given that you only want the last group, (Teacher|Professor|Student|NoRole), the other 4 groups should be marked as non-capturing groups. This is done by adding a ?: after the opening parenthesis:

    Given(/^I (?:\w{2})?\s?(?:log|login|logged)\s?(?:\w{2}) as (?:an|a) "(Teacher|Professor|Student|NoRole|Owner)"\.?$/)
    

    Note that the "Owner" role was missing from the user_role group (and is added above). This step will match all 5 of the expected steps.