I have been developing a sample application after reading Rails 3 Tutorial book. In this application there are many Sections and each section has one Video.
Here are the artifacts of this application:
Models
class Video < ActiveRecord::Base
has_many :sections
end
class Section < ActiveRecord::Base
belongs_to :video
validates :name, presence: true, length: { maximum: 50 }
end
RSpec
require 'spec_helper'
describe Section do
let(:video) { Video.new(name: "Dummy Video Name", path: "/home/data/video/test.mov") }
before do
@section = video.sections.build(name: 'Test Section')
end
subject { @section }
# Check for attribute accessor methods
it { should respond_to(:name) }
it { should respond_to(:video) }
it { should respond_to(:video_id) }
its(:video) { should == video }
# Sanity check, verifying that the @section object is initially valid
it { should be_valid }
describe "when name is not present" do
before { @section.name = "" }
it { should_not be_valid }
end
describe "when name is too long" do
before { @section.name = "a" * 52 }
it { should_not be_valid }
end
describe "when video_id not present" do
before { @section.video_id = nil }
it { should_not be_valid }
end
...
end
And the schema definitions of both Models
..
create_table "sections", :force => true do |t|
t.string "name"
t.integer "video_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "videos", :force => true do |t|
t.string "name"
t.string "path"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
...
While running above rspec I am getting following error.
Failures:
1) Section
Failure/Error: it { should be_valid }
expected valid? to return true, got false
# ./spec/models/section_spec.rb:22:in `block (2 levels) in <top (required)>'
2) Section video
Failure/Error: its(:video) { should == video }
expected: #<Video id: nil, name: "Dummy Video Name", path: "/home/data/video/test.mov", created_at: nil, updated_at: nil>
got: nil (using ==)
# ./spec/models/section_spec.rb:19:in `block (2 levels) in <top (required)>'
I could map my requirement with User-Micropost relation describe in the book and aligned RSpec with them. I have limited knowledge on Rails and the whole echo system.
Please help me to resolve this issue and some reference to validation Models with RSpec(and shoulda) is highly appreciable.
- Amit Patel
I am able to resolve this issue by saving video in
beforeblock.Here is the snippet
The only difference between the Micropost model spec of Rails 3 Tutorial book and the above one is , the former one is using FactoryGirl#create. From https://github.com/thoughtbot/factory_girl/wiki/How-factory_girl-interacts-with-ActiveRecord I found that FactoryGirl.create method actually creates and save instance internally. So it was working there while it was no working in my code.
If you have better insight with RSpec for ActiveRecord then please share with us.
Thanks.
Amit Patel