spock: where block cannot access or declare variables?

Originally reported on Google Code with ID 15

i would expect to be able to do this:

def "my test"() {
  given:
      def a = new Apple()
      def o = new Orange()

  when:
      fruit = f
  then: 
      <something>
  where:
       f << [a, o, a, o, a, o]  
}

But I get MissingPropertyException for a & o.  I also tried declaring a & o in the
where block - same issue.  Declaring them outside the 
scope of the method works but is not ideal.  I ended up unrolling the where into several
when/then blocks.

I see that the documentation for the where block is coming (at light speed :) so maybe
this is as designed.

Thanks

Reported by jacobsonz on 2009-03-12 18:07:08

About this issue

  • Original URL
  • State: open
  • Created 9 years ago
  • Reactions: 1
  • Comments: 22 (13 by maintainers)

Most upvoted comments

+1 for this feature!

@Vampire if you want to tackle that, you can give it a try. I think that they would basically behave like scoped constants that are available only to the where block. Furthermore, to make it less confusing I would say you can only declare them as first expressions of a where block. Maybe we should require final instead of def to make it clear that they won’t be reassigned.

where:
final sep = "."

path              | startsWithPath || result
""                | ""             || true
"a${sep}a${sep}a" | "a${sep}b"     || false
"a${sep}a"        | "a${sep}a"     || true

The following would be illegal:

where:
a | b
1 | 2

final c = a + b
d << [c, c]

Sorry for the late answer @wisnij. I think in 1.3 it should have worked iirc, but since 2.0 it will not anymore due to various quirks and problems it caused and various cases that did not work anyway as you can read in the 2.0 migration guide: https://spockframework.org/spock/docs/2.3/all_in_one.html#_no_access_to_data_variables_in_data_pipes_anymore_2

As @leonard84 mentioned, you can declare expected as @Shared or static (if it is a constant) field and then access it in the where block.

@leonard84 maybe now that we forbid to access other data variables it might be time to actually reopen this issue and finally allow local variables in the where block? What do you think?