2014-09-29 77 views
0

好了,所以我有模型,我填充我的SQLite数据库在我seeds.rb这里是代码如何在rails中访问我的数据库的内容?

〜/元素周期表/ DB/seeds.rb

# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). 
# 
# Examples: 
# 
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) 
# Mayor.create(name: 'Emanuel', city: cities.first) 
File.open("pt-data3.csv", 'r').each_line do |line| 
    temp = line.split(',') 
    Element.create(proton: temp[0].strip, symbol: temp[1].strip, name: temp[2].strip, mass: temp[3].strip) 
end 

然后我试图访问它的我的RSpec的,我不断收到为零,这是我的RSpec

〜/元素周期表/规格/型号/ element_spec.rb

require 'rails_helper' 

RSpec.describe Element, :type => :model do 
    it "should contain the right elements" do 
     expect(Element.find_by(proton: 1)).to include("Hydrogen") 
    end 
end 

然而Element.find_b无论我输入什么东西,都会一直返回零。我的数据库确实存在,因为我查了。当我在rails console中做Element.find_by时,它工作得很好。我可以正确得到所有的元素在我的rails控制台但是当我把它放在我的Rails应用的任何Element.find_by总是返回零

这里也是我的模型类,如果其任何关联

〜/元素周期表/应用/型号/element.rb

class Element < ActiveRecord::Base 
end 

回答

1

Rails在生产,开发和测试中维护不同的数据库。这意味着你认为应该在那里的数据存在于你的开发数据库中。如果您想在测试中访问数据,则需要将其保存在测试环境中。考虑使用FactoryGirl在测试数据库中创建对象。

+1

或者你也可以运行RAILS_ENV = test rake db:seed – 2014-09-29 03:19:15

相关问题