Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

class Company < ActiveRecord::Base
end

spec/factories/companies.rb

FactoryGirl.define do
  factory :company do
    name "MyString"
  end
end

spec/models/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

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
like image 651
Hiroaki Machida Avatar asked Jun 26 '14 11:06

Hiroaki Machida


1 Answers

Ah, got burnt by this a couple of times.

let expressions are lazily evaluated. You didn't reference that one, so the company never got created. You can use let!, for example.

  let!(:company) { FactoryGirl.create(:company) }

Or reference that 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
like image 81
Sergio Tulentsev Avatar answered Nov 06 '22 18:11

Sergio Tulentsev