我正在尝试构建一个Rspec套件来测试我的Article类中的方法'filter'。我知道通过第一手使用这个类方法在生产中完美地执行,但是当在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
答案 0 :(得分: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