我一直在关注 Rails 教程(http://railstutorial.org/chapters/beginning,Rails 3 版本),当使用 Factory Girl 和 Rspec 时,我已经停在第 11 章,我有一个没有通过的测试我觉得我做错了什么,但我不明白是什么。
首先,Github 上有一个 git 存储库,其中包含未通过该测试的代码。
http://github.com/Monomachus/ch3_static_pages
所以我得到了用户模型
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
has_many :microposts
.
.
.
我有微博模型
class Micropost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
default_scope :order => 'microposts.created_at DESC'
end
然后我得到了工厂女孩设置
Factory.define :user do |user|
user.name "Michael Hartl"
user.email "mhartl@example.com"
user.password "foobar"
user.password_confirmation "foobar"
end
Factory.define :micropost do |micropost|
micropost.content "Foo bar"
micropost.association :user
end
最后是 Rspec 代码
require 'spec_helper'
describe Micropost do
.
.
describe "microposts associations" do
before(:each) do
@user = User.create(@attr)
@mp1 = Factory(:micropost, :user => @user, :created_at => 1.day.ago)
@mp2 = Factory(:micropost, :user => @user, :created_at => 1.hour.ago)
end
it "should have a microposts attribute" do
@user.should respond_to(:microposts)
end
it "should be in the reverse order of appearing" do
@user.microposts.should == [@mp2, @mp1]
end
end
end
我得到了一个错误,它肯定告诉我我做错了什么。
Failures:
1) Micropost microposts associations should be in the reverse order of appearing
Failure/Error: @user.microposts.should == [@mp2, @mp1]
expected: [#<Micropost id: 2, content: "Foo bar", user_id: nil, created_at: "2010-12-24 12:47:02", update
d_at: "2010-12-24 13:47:02">, #<Micropost id: 1, content: "Foo bar", user_id: nil, created_at: "2010-12-23 13:
47:02", updated_at: "2010-12-24 13:47:02">],
got: [] (using ==)
Diff:
@@ -1,3 +1,2 @@
-[#<Micropost id: 2, content: "Foo bar", user_id: nil, created_at: "2010-12-24 12:47:02", updated_at: "20
10-12-24 13:47:02">,
- #<Micropost id: 1, content: "Foo bar", user_id: nil, created_at: "2010-12-23 13:47:02", updated_at: "20
10-12-24 13:47:02">]
+[]
# ./spec/models/micropost_spec.rb:42:in `block (3 levels) in <top (required)>'
如您所见,即使 user_id 属性设置不正确+
显然@user.microposts 没有任何元素。
请帮我解决这个问题谢谢。