我正在研究Michael Hartl的rails教程。运行测试时,出现以下错误:
Error:
UserTest#test_associated_microposts_should_be_destroyed:
ArgumentError: unknown command 'a'
test/models/user_test.rb:73:in 'test'
test/models/user_test.rb:73: in 'block in <class:UserTest>'
"test/models/user_test.rb"如下:
test "associated microposts should be destroyed" do
@user.save
@user.microposts.create!(content: "Lorem ipsum")
assert_difference 'Micropost.count', -1 do
@user.destroy
end
该测试很简单,仅用于在我的模型中测试以下行 (user.rb)
has_many :microposts, dependent: :destroy
如果我这样评论这句话:
has_many :microposts#, dependent: :destroy
正如预期的那样,我得到了
Failure: [...] "Micropost.count" didn't change by -1. Expected:38 Actual 39.
如果我取消注释"依赖::d estroy"语句,则会出现此"未知命令"错误。任何人都可以就此错误最有可能是如何生成的,在 rails 上下文(不包括 rails 控制台)中的"命令"是什么以及首先在哪里尝试解决它(模型?控制器?谢谢。
您的assert_difference通话中有拼写错误。
assert_difference 'Micropost.count" ...
请注意开头的单引号和结尾的双引号。
我重新处理了我的代码,并通过删除每个测试注意到,即使失败日志中只报告了一个测试,我也可以通过分别删除测试文件底部的两个不同测试中的任何一个来摆脱失败,如下所示:
test "associated microposts should be destroyed" do
@user.save
@user.microposts.create!(content: "Lorem ipsum")
assert_difference 'Micropost.count', -1 do
@user.destroy
end
test "authenticated? should return false for a user with nil digest" do
assert_not @user.authenticated?(:remember, '')
end
end
.
.
问题是其中一个"结尾"放错了地方。该文件应为:
test "associated microposts should be destroyed" do
@user.save
@user.microposts.create!(content: "Lorem ipsum")
assert_difference 'Micropost.count', -1 do
@user.destroy
end
end
test "authenticated? should return false for a user with nil digest" do
assert_not @user.authenticated?(:remember, '')
end
我仍然有兴趣了解为什么失败日志检索到"未知命令'a'"以提高我对未来轨道测试环境的理解。
我刚才遇到了同样的问题,还有这个;
在micropost_test.rb
的顶部有这个设置
//first post creation for @user
def setup
@user = users(:michael)
# This code is not idiomatically correct.
@micropost = @user.microposts.build(content: "Lorem ipsum")
end
//second post creation in test for @user
test "associated microposts should be destroyed" do
@user.save
@user.microposts.create!(content: "Lorem ipsum")
assert_difference 'Micropost.count', -1 do
@user.destroy
end
那里已经创建了一个帖子,因此当用户与测试中的另一个帖子一起保存时,该用户被删除,实际上他的 2 个帖子已经消失了。所以我们期望的应该是-2的差异。