0

This is the correct code for testing if clicking a button changed the # of users:

expect { click_button "Create my account" }.not_to change(User, :count) (correct)

But the curly braces seem so strangely placed above. Why does Capybara use the above syntax and not the below syntax?

expect { click_button("Create my account").not_to change(User, :count) } (incorrect)

Andrei Botalov
  • 20,686
  • 11
  • 89
  • 123
Don P
  • 60,113
  • 114
  • 300
  • 432

2 Answers2

0

expect {} is specifying a code block which after execution is tested against the change keyword. See https://rspec.info/blog/2012/06/constant-stubbing-in-rspec-2-11/

Dave Powers
  • 2,051
  • 2
  • 30
  • 34
mentat
  • 102
  • 6
0

Every Ruby method takes a block. Blocks are indicated with either a do...end construct or curly braces.

def my_method
  yield
end

my_method { puts "hello world" }
"hello world"
=> nil

my_method do
  puts "hello world again!"
end
"hello world again!"
=> nil

expect in this case is an RSpec matcher, not a Capybara method. The curly braces mean you are defining code that will execute at some later time. In this case, it will be executed in between two calls to some equivalent of User.count.

# approximation of what RSpec is doing with `expect` curly braces.
count = User.count
yield # executes code in curly braces
new_count = User.count
assert(count == new_count)
Community
  • 1
  • 1
steel
  • 11,883
  • 7
  • 72
  • 109