Pra*_*nth 3 ruby post ruby-on-rails
我来自 Python 和 Java 背景,只有 CSS、HTML、Ruby 的基本知识,并尝试使用 Ruby on Rails 学习 Web 开发。我正在尝试按照Michael Hartl上的教程进行操作。我不明白代码post清单 7.23 中的方法在做什么参数。
require 'test_helper'
class UsersSignupTest < ActionDispatch::IntegrationTest
test "invalid signup information" do
get signup_path
assert_no_difference 'User.count' do
post users_path, params: { user: { name: "",
email: "user@invalid",
password: "foo",
password_confirmation: "bar" } }
end
assert_template 'users/new'
end
end
Run Code Online (Sandbox Code Playgroud)
从我在API 中的跟踪来看,它接受了两个都是字符串的非可选参数,但是在代码清单 7.23params:中,第二个参数中突然出现了哈希语法,这让我很困惑。任何人都可以启发我吗?
我认为您看错了地方,链接显示http.post。你想要IntegrationTest post.
来自:https : //github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/testing/integration.rb
def post(path, **args)
process(:post, path, **args)
end
Run Code Online (Sandbox Code Playgroud)
和:
def process(method, path, params: nil, headers: nil, env: nil, xhr: false, as: nil)
request_encoder = RequestEncoder.encoder(as)
headers ||= {}
# rest
end
Run Code Online (Sandbox Code Playgroud)
编辑:双啪
Ruby 2.0 添加了关键字参数和双拼音。当您有未知数量的参数时,基本上使用单个 splat (*),并将其作为array.
def with_args(*args)
p args
end
with_args(1,2,"a")
# [1, 2, "a"]
Run Code Online (Sandbox Code Playgroud)
double splat (**) 的作用类似于 *,但对于关键字参数:
def with_args(**args)
with_keyword(args)
end
def with_keyword(some_key: nil, other_key: nil)
p "some_key: #{some_key}, other_key: #{other_key}"
end
with_args(some_key: "some_value", other_key: "other_value")
# "some_key: some_value, other_key: other_value"
with_args(some_key: "some_value")
# "some_key: some_value, other_key: "
Run Code Online (Sandbox Code Playgroud)
在 ruby 中,您可以在没有 的情况下调用方法()并在没有 的情况下传递散列{},因此
with_args({some_key: "some_value", other_key: "other_value"})
Run Code Online (Sandbox Code Playgroud)
就像写作
with_args some_key: "some_value", other_key: "other_value")
Run Code Online (Sandbox Code Playgroud)
请参阅此答案:双 * (splat) 运算符做什么 和https://medium.freecodecamp.org/rubys-splat-and-double-splat-operators-ceb753329a78
所以...
写作时
post users_path, params: { user: { name: "",
email: "user@invalid",
password: "foo",
password_confirmation: "bar" } }
Run Code Online (Sandbox Code Playgroud)
是否调用处理
process(:post, users_path, params: { user: { name: "",
email: "user@invalid",
password: "foo",
password_confirmation: "bar" } }
Run Code Online (Sandbox Code Playgroud)
中的含义process,params是散列
{ user: { name: "",
email: "user@invalid",
password: "foo",
password_confirmation: "bar" } }
Run Code Online (Sandbox Code Playgroud)
进程的其他关键字参数无关紧要,散列是 all params,所有其他关键字都为零
希望这是有道理的...