为什么这个where()。first_or_create只在RSpec中生成错误的SQL?

时间:2012-03-23 21:14:25

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

我看到Action.where(:name => "fred").first_or_create在RSpec下运行时生成错误的SQL但在控制台中正确执行的情况。我很困惑。

这是模型。底层actions表有一个字段,一个名为name的字符串:

# file: app/models/action.rb
class Action < ActiveRecord::Base
  def self.internalize(name)
    self.where(:name => name).first_or_create
  end
end

这是rspec测试:

# file: spec/models/action_spec.rb
require 'spec_helper'
describe Action do
  describe 'intern' do
    it 'should create a new name' do  # works
      lambda { Action.internalize("fred") }.should change { Action.count }.by(1)
    end
    it 'should not create duplicate names' do  # fails
      Action.internalize(:name => "fred")
      lambda { Action.internalize("fred") }.should_not change { Action.count }
    end
  end
end

这是失败:

1) Action intern should not create duplicate names
   Failure/Error: Action.internalize(:name => "fred")
   ActiveRecord::StatementInvalid:
     PG::Error: ERROR:  missing FROM-clause entry for table "name"
     LINE 1: SELECT  "actions".* FROM "actions"  WHERE "name"."name" = 'f...
     : SELECT  "actions".* FROM "actions"  WHERE "name"."name" = 'fred' LIMIT 1
   # ./app/models/action.rb:4:in `internalize'
   # ./spec/models/action_spec.rb:12:in `block (3 levels) in <top (required)>'

当记录存在时,Action.where(:name => "fred").first_or_create正在生成SQL

SELECT "actions".* FROM "actions" WHERE "name"."name" = 'fred' LIMIT 1

......这是错的 - 它正在寻找一个名为“name”的表。

奇怪的是,在控制台中键入完全相同的内容可以正常运行。是的,我记得(这次)在运行我的RSpec测试之前键入rake db:test:prepare。我正在跑步

Ruby version              1.9.3 (x86_64-darwin10.8.0)
Rails version             3.2.1
RSpec                     2.9.0

这到底是怎么回事?

1 个答案:

答案 0 :(得分:1)

Action.internalize(:name => "fred")正在生成where子句:

where(:name => {:name => "fred"})

这意味着,您有关联的表name,其列name的值为fred