Reputation: 96594
I have an Active Record based model:- House
It has various attributes, but no formal_name
attribute.
However it does have a method for formal_name
, i.e.
def formal_name
"Formal #{self.other_model.name}"
end
How can I test that this method exists?
I have:
describe "check the name " do
@report_set = FactoryGirl.create :report_set
subject { @report_set }
its(:formal_name) { should == "this_should_fail" }
end
But I get undefined method 'formal_name' for nil:NilClass
Upvotes: 3
Views: 4400
Reputation: 12273
Personally, I'm not a fan of the shortcut rspec syntax you're using. I would do it like this
describe '#formal_name' do
it 'responds to formal_name' do
report_set = FactoryGirl.create :report_set
report_set.formal_name.should == 'formal_name'
end
end
I think it's much easier to understand this way.
# model - make sure migration is run so it's in your database
class Video < ActiveRecord::Base
# virtual attribute - no table in db corresponding to this
def embed_url
'embedded'
end
end
# factory
FactoryGirl.define do
factory :video do
end
end
# rspec
require 'spec_helper'
describe Video do
describe '#embed_url' do
it 'responds' do
v = FactoryGirl.create(:video)
v.embed_url.should == 'embedded'
end
end
end
$ rspec spec/models/video_spec.rb # -> passing test
Upvotes: 1
Reputation: 1282
First you probably want to make sure your factory is doing a good job creating report_set -- Maybe put factory_girl under both development and test group in your Gemfile, fire up irb to make sure that FactoryGirl.create :report_set
does not return nil.
Then try
describe "#formal_name" do
let(:report_set) { FactoryGirl.create :report_set }
it 'responses to formal_name' do
report_set.should respond_to(:formal_name)
end
it 'checks the name' do
report_set.formal_name.should == 'whatever it should be'
end
end
Upvotes: 3