为什么这个rspec测试在应该通过时失败?

时间:2011-02-28 00:53:55

标签: ruby-on-rails ruby ruby-on-rails-3 rspec feeds

我正在关注http://ruby.railstutorial.org/chapters/following-users#code:from_users_followed_by_final并且这些测试失败了:

        describe "status feed" do

        it "should have a feed" do
          @user.should respond_to(:feed)
        end

        it "should include the user's microposts" do
          @user.feed.include?(@mp1).should be_true
          @user.feed.include?(@mp2).should be_true
        end

        it "should not include a different user's microposts" do
          mp3 = Factory(:micropost,
                        :user => Factory(:user, :email => Factory.next(:email)))
          @user.feed.include?(mp3).should be_false
        end
      end
    end  

以下是错误:

 1) status feed should have a feed
 Failure/Error: @user.should respond_to(:feed)
   expected nil to respond to :feed
 # ./spec/models/user_spec.rb:170

 2) status feed should include the user's microposts
   Failure/Error: @user.feed.should include(@mp1)
    NoMethodError:
     undefined method `feed' for nil:NilClass
    # ./spec/models/user_spec.rb:174

 3) status feed should not include a different user's microposts
    Failure/Error: @user.feed.should_not include(mp3)
    NoMethodError:
    undefined method `feed' for nil:NilClass
    # ./spec/models/user_spec.rb:181

  4) status feed should include the microposts of followed users
   Failure/Error: @user.follow!(followed)
   NoMethodError:
    undefined method `follow!' for nil:NilClass
    # ./spec/models/user_spec.rb:187

这是我的micropost.rb文件:

class Micropost < ActiveRecord::Base
attr_accessible :content

belongs_to :user

validates :content, :presence => true, :length => { :maximum => 140 }
validates :user_id, :presence => true

def self.from_users_followed_by(user)
  followed_ids = user.following.map(&:id).join(", ")
  where("user_id IN (#{followed_ids}) OR user_id = ?", user)
end

default_scope :order => 'microposts.created_at DESC'

# Return microposts from the users being followed by the given user.
scope :from_users_followed_by, lambda { |user| followed_by(user) }

private

  # Return an SQL condition for users followed by the given user.
  # We include the user's own id as well.
  def self.followed_by(user)
    followed_ids = %(SELECT followed_id FROM relationships
                     WHERE follower_id = :user_id)
    where("user_id IN (#{followed_ids}) OR user_id = :user_id",
          { :user_id => user })
  end
end 

这是我的pages_controller.rb文件中的home方法:

def home
@title = "Home"
if signed_in?
  @micropost = Micropost.new
  @feed_items = current_user.feed.paginate(:page => params[:page])
 end
end

这是我在user.rb中的Feed方法

    def feed
     Micropost.from_users_followed_by(self)
    end

如果我要重现更多代码,请告诉我。

1 个答案:

答案 0 :(得分:1)

在测试中引用它之前,您没有设置@user。这需要设置为User对象。这是先前在describe "relationsips"块中设置的,但似乎没有在那里设置。