很确定这些测试工作正常.通过在user.rb中移除has_many:relationships和has_many:reverse_relationships上的dependent :: destroy选项让它们失败.
希望分享我所做的事情,万一其他人正在通过Michael Hartl’s Rails Tutorial 2nd Edition,Chapter 11 Exercises.工作
这个练习产生了一些问题(见本文的底部).如果有人能提供帮助,那就太好了.
第11章,练习1:
按照清单10.15中的示例,在Relationship模型(清单11.4和清单11.16)中添加依赖关系:destroy的测试.
这是我的测试:
规格/型号/ user_spec.rb
require 'spec_helper' describe User do before do @user = User.new(name: "Example User",email: "user@example.com",password: "foobar",password_confirmation: "foobar") end subject { @user } [...code omitted...] describe "relationship associations" do let(:other_user) { FactoryGirl.create(:user) } before do @user.save @user.follow!(other_user) other_user.follow!(@user) end it "should destroy associated relationships" do relationships = @user.relationships @user.destroy relationships.should be_empty end it "should destroy associated reverse relationships" do reverse_relationships = @user.reverse_relationships @user.destroy reverse_relationships.should be_empty end end
这个练习产生了几个问题:
问题1:
我最初的测试是
relationships.should be_nil
reverse_relationships.should be_nil
但是,尽管没有用户存在,但实现了数组仍在返回.
那么,当用户不存在并且调用关联方法时,结果仍然是数组?这总是如此吗?
问题2:
我想在rails控制台中为用户删除关系和reverse_relationship.
我试过这个
> user = User.first > user.relationships # returns a bunch of relationships > user.relationships.destroy => [] > user.relationships # returns same bunch of relationships
我如何永久地破坏关系?在控制台中探索时,这似乎是件好事.
谢谢!我还是Rails的新手
解决方法
我也是ruby/铁路菜鸟.
问题1:
搜索rubyonrails.org for has_many,它说
Returns an array of all the associated objects. An empty array is returned if none are found.
另外,您可以测试nil和empty:
relationships.present?.should be_false
问题2:
user.relationships.destroy需要:id
user.relationships.destroy '1'