3
我看到一个案例,其中Action.where(:name => "fred").first_or_create
在RSpec下运行时生成不正确的SQL,但在控制台中正确执行。我很困惑。这是为什么where()。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
......这是错误的 - 它正在寻找名为“名称”的表。
奇怪的是,在控制台中输入完全相同的东西会正常运行。是的,我记得(这次)在运行我的RSpec测试之前输入rake db:test:prepare
。我正在运行
Ruby version 1.9.3 (x86_64-darwin10.8.0)
Rails version 3.2.1
RSpec 2.9.0
这是怎么回事?
这意味着,它的工作原理Rails的控制台上的事实是幸运的巧合。 – 2012-03-25 02:51:05
@Mik:请解释一下?据我所知,'Action.internalize(:name =>“fred”)'生成where子句'Action.where(:name =>“fred”)',否? [见http://guides.rubyonrails.org/active_record_querying.html#hash-conditions]。你在哪里得到嵌套散列? – 2012-03-25 05:56:19
@Mik:OOHHHHH!是的,这是我的一个非常愚蠢的错字。对Action.internalize(:name =>“fred”)的调用应该只是Action.internalize(“fred”)。你不知道我有多少次盯着那段代码,完全错过了它。 – 2012-03-25 06:50:41