[英]FactoryGirl records are not saved
I'm trying to write tests, on which company objects are saved. 我正在尝试编写测试,保存公司对象。 But, company objects are not saved, and there is no company record on the table. 但是,公司对象未保存,并且表中没有公司记录。 Why and how can I fix the problem? 为什么以及如何解决问题?
db/schema.rb DB / schema.rb
ActiveRecord::Schema.define(version: 20140626075006) do
create_table "companies", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
end
app/models/company.rb 应用程序/模型/ company.rb
class Company < ActiveRecord::Base
end
spec/factories/companies.rb 规格/工厂/ companies.rb
FactoryGirl.define do
factory :company do
name "MyString"
end
end
spec/models/company_spec.rb 规格/型号/ company_spec.rb
require 'spec_helper'
describe Company do
let(:company) { FactoryGirl.create(:company) }
context "test context"do
it "test" do
Company.first.name
end
end
end
spec/spec_helper.rb 投机/ spec_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
RSpec.configure do |config|
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_base_class_for_anonymous_controllers = false
config.order = "random"
end
result 结果
/Users/machidahiroaki/.rvm/rubies/ruby-2.0.0-p451/bin/ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /Users/machidahiroaki/RubymineProjects/rspec_sample/bin/rake spec
Testing started at 19:48 ...
/Users/machidahiroaki/.rvm/rubies/ruby-2.0.0-p451/bin/ruby -S rspec ./spec/bowling_spec.rb ./spec/models/company_spec.rb
NoMethodError: undefined method `name' for nil:NilClass
./spec/models/company_spec.rb:7:in `block (3 levels) in <top (required)>'
2 examples, 1 failure, 1 passed
Finished in 0.090546 seconds
/Users/machidahiroaki/.rvm/rubies/ruby-2.0.0-p451/bin/ruby -S rspec ./spec/bowling_spec.rb ./spec/models/company_spec.rb failed
Process finished with exit code 1
Ah, got burnt by this a couple of times. 啊,被这几次烧了。
let
expressions are lazily evaluated. let
表达式被懒惰地评估。 You didn't reference that one, so the company
never got created. 你没有引用那个,所以company
从未创建过。 You can use let!
你可以用let!
, for example. , 例如。
let!(:company) { FactoryGirl.create(:company) }
Or reference that company
或者参考那company
let(:company) { FactoryGirl.create(:company) }
context "test context"do
it "test" do
expect(company).to_not be_nil
expect(Company.count).to eq 1
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.