我正在尝试编写测试,保存公司对象。但是,公司对象未保存,并且表中没有公司记录。为什么以及如何解决问题?
分贝/ 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
应用程序/模型/ company.rb
class Company < ActiveRecord::Base
end
规格/工厂/ companies.rb
FactoryGirl.define do
factory :company do
name "MyString"
end
end
规格/模型/ 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_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
结果
/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
答案 0 :(得分:9)
let
表达式被懒惰地评估。你没有引用那个,所以company
永远不会被创建。例如,您可以使用let!
。
let!(:company) { FactoryGirl.create(: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