在命名空间模型上将factory_girl_rails与Rspec一起使用 [英] Using factory_girl_rails with Rspec on namespaced models

查看:84
本文介绍了在命名空间模型上将factory_girl_rails与Rspec一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网络服务,可以向几个不同的客户投放广告.广告的结构因客户端而异,因此,我通过客户端名称在模型和控制器上使用名称空间来区分广告.从高层次看,它是这样的:

I have a web service that serves Ads to several different clients. The structure of the Ad varies between clients, and therefore, I am using namespaces for my models and controllers by the client name to differentiate between Ads. From the high level, it looks like this:

'app/models/client1/ad.rb'

class Client1::Ad < ActiveRecord::Base
  attr_accessible :title, :description
end

'app/models/client2/ad.rb'

class Client2::Ad < ActiveRecord::Base
  attr_accessible :title, :description, :source
end

实际上,这些模型更复杂并且具有关联性,但这不是重点.
我正在使用rspec-rails 2.4.0和factory_girl_rails 1.0.1编写一些单元测试,并且我所有的工厂都工作得很好.但是,我无法为命名空间模型定义工厂.我已经尝试过类似的方法:

In reality, these models are more complex and have associations, but that is not the point.
I am writing some unit tests using rspec-rails 2.4.0 and factory_girl_rails 1.0.1, and all of my factories work great. However, I am not able to define factories for the namespaced models. I've tried something like:

Factory.define :client1_ad, :class => Client1::Ad do |ad|
  ad.title       "software tester"  
  ad.description "Immediate opening"
end  

Factory.define :client2_ad, :class => Client2::Ad do |ad|
  ad.title       "software tester"  
  ad.description "Immediate opening"
  ad.source      "feed"
end

它没有完成任务.我环顾四周,但是看到的每个示例都使用了非命名空间模型.有人有想法么?任何输入,我们将不胜感激.

It didn't do the job. I looked around, but every single example that I saw was using non-namespaced models. Anyone have any ideas? Any input is greatly appreciated.

推荐答案

在这里我有一个最小的工作示例,也许您可​​以使用它来查明问题出在哪里.您在dmarkow答案中留下的评论向我暗示您在其他地方有错误.

I have a minimal working example here, maybe you could use it to pinpoint where your problem is. The comment you left on dmarkow's answer suggests to me that you have an error someplace else.

app/models/bar/foo.rb

class Bar::Foo < ActiveRecord::Base
end

* db/migrate/20110614204536_foo.rb *

*db/migrate/20110614204536_foo.rb*

class Foo < ActiveRecord::Migration
  def self.up
    create_table :foos do |t|
      t.string :name
    end
  end

  def self.down
    drop_table :foos
  end
end

spec/factories.rb

Factory.define :foo, :class => Bar::Foo do |f|
  f.name 'Foooo'
end

* spec/models/foo_spec.rb *

*spec/models/foo_spec.rb*

require 'spec_helper'

describe Bar::Foo do

  it 'does foo' do
    foo = Factory(:foo)
    foo.name.should == 'Foooo'
  end
end

运行测试:

$ rake db:migrate
$ rake db:test:prepare
$ rspec  spec/models/foo_spec.rb 
.

Finished in 0.00977 seconds
1 example, 0 failures

希望有帮助.

这篇关于在命名空间模型上将factory_girl_rails与Rspec一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆