0

我正在尝试构建一个 Rspec 套件来测试我的 Article 类上的方法“过滤器”。我通过第一手使用知道这个类方法在生产中完美执行,但是在 rspec 中运行时它只返回一个空白数组。任何想法为什么会这样?

describe '.filter' do
    it 'filters by user' do
      ActiveRecord::Base.logger = Logger.new(STDOUT) if defined?(ActiveRecord::Base)
      user1 = User.create!(username: 'user1', status: 1)
      article1 = Article.create!(user_id: user1.id)
      Article.filter({writer: 'user1'}).should == article1
    end
  end

这是文章的类过滤器。

def self.filter(hash)
    # need to make case insensitive
    hash.delete_if {|k,v| v == ""}
    hash[:writer_type] = (hash[:writer_type]) if hash[:writer_type] != nil
    sql_base = "select distinct articles.* from articles
       join tags
       on tags.article_id = articles.id
       join categories
       on tags.category_id = categories.id
       left outer join itineraries
       on itineraries.article_id = articles.id
       left outer join cities
       on itineraries.city_id = cities.id
       join users
       on users.id = articles.user_id"

    condition_array = []
    key_array = []
    hash.each_key {|key| key_array << key}
    key_array.each_with_index do |key, i|
      operator = "and"
      operator = "where" if i == 0
      case key
      when :writer
        sql_base << "\n#{operator} users.username like ?"
        condition_array << hash[:writer]
      when :writer_type
         sql_base << "\n#{operator} users.status in (?)"
        condition_array << hash[:writer_type]
      when :city
        sql_base << "\n#{operator} cities.name like ?" 
        condition_array << hash[:city]
      when :category
        sql_base << "\n#{operator} categories.name like ?"
        condition_array << hash[:category]
      end
    end
    sql_array = [sql_base,condition_array].flatten
    articles = Article.find_by_sql(sql_array)
    articles
  end
4

1 回答 1

0

看起来:username不是该方法的参数。我明白:writer了,也许是这个?

describe '.filter' do
  it 'filters by user' do
    ActiveRecord::Base.logger = Logger.new(STDOUT) if defined?(ActiveRecord::Base)
    user1 = User.create!(username: 'user1', status: 1)
    article1 = Article.create!(user_id: user1.id)
    expect(Article.filter({writer: user1.username})).to eql([article1])
  end
end
于 2013-09-12T15:41:48.777 回答