创建一个模型方法,计算用户的帖子并在rspec(Rails)中测试?

时间:2016-05-28 20:44:48

标签: ruby-on-rails rspec

我正在尝试创建一个模型方法来计算用户的帖子数量,然后使用Rspec进行测试。

但我遇到了错误,

undefined method `count_posts' for #<User:0x000000044d42a8>

用户模型

has_many :posts

def self.count_posts
  self.posts.all.count
end

帖子模型

belongs_to :user

User_spec.rb

require 'rails_helper'
RSpec.describe User, type: :model do
  describe "count_posts" do

      before do
          @user1 = create(:user)
          post = create(:post, user: @user1)
      end

      it "Returns number of posts for a user" do
        expect( @user1.count_posts ).to eq(1)
      end
  end
end

/factories/users.rb

FactoryGirl.define do
  factory :user do
    sequence(:email, 100) { |n| "person#{n}@example.com"}
    password "helloworld"
    password_confirmation "helloworld"
  end
end

/factories/posts.rb

FactoryGirl.define do
  factory :post do
    title "Post Title"
    body "Post bodies must be pretty long."
    user
  end
end

我不明白为什么它是一个未定义的方法,除非我在模型中错误地写了它(我完全接受它)。

如果这个问题过于新鲜,请提前道歉。但我还没有完全掌握Rspec测试或使用self

1 个答案:

答案 0 :(得分:1)

根据您的逻辑,count_posts必须是实例方法而不是类方法:

class User < ActiveRecord::Base
  has_many :posts

  def count_posts
    posts.count # or posts.size
  end
end