使用大括号的单行 shoulda 语法 [英] One-liner shoulda syntax using braces

查看:43
本文介绍了使用大括号的单行 shoulda 语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Rails Test Prescriptions(b10.0,第 176 页)一书中,有如下单行断言示例:

In the book Rails Test Prescriptions (b10.0, page 176), there are examples of one-liner assertions like the following:

应该成功"{ assert_response :success }

这对我来说似乎不是有效的 ruby​​ 语法,并且 ruby​​ 报告左大括号是意外的.为了解析它,我必须把它改成

This doesn’t appear to be valid ruby syntax to me, and ruby reports that the left curly brace is unexpected. In order for it to be parsed, I have to change it to

应该成功";做 assert_response : 成功结束

第一个例子的语法有什么问题?

What's wrong with the syntax of the first example?

推荐答案

这是有效的 Ruby 语法.嗯,有点.简直没道理!

This is valid Ruby syntax. Well, sort of. It just doesn't make sense!

由于使用大括号的文字块的优先级高于传递不带括号的参数,因此块被绑定到参数而不是方法调用.如果参数本身是一个方法调用,那么您甚至不会收到语法错误.你会想知道为什么你的块没有被调用.

Since the precedence of a literal block using curly braces is higher than passing an argument without parentheses, the block gets bound to the argument instead of the method call. If the argument is itself a method call, then you won't even get a syntax error. You'll just scratch your head wondering why your block doesn't get called.

为了解决这个问题,你要么在参数周围加上括号,因为括号的优先级高于大括号,或者使用 do/end 形式,这是较低的优先级而不是没有括号的参数列表.

To fix this, you either put parentheses around the argument, since parentheses have higher precedence than curly braces, or use the do / end form, which is lower precedence than an argument list without parentheses.

def foo; yield if block_given?; 'foo' end

puts foo { puts 'block' }
# block
# foo

puts(foo) { puts 'block' }
# foo

puts foo do puts 'block' end
# foo

puts foo { puts 'block' }, foo { puts 'block' }
# block
# block
# foo
# foo

puts 'foo' { puts 'block' }
# SyntaxError: (irb):19: syntax error, unexpected '{', expecting $end

这篇关于使用大括号的单行 shoulda 语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆