Search code examples
ruby-on-railsrubyrspecrspec-railsexpectations

rspec - how to test for a model attribute that is not a database column


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


Solution

  • 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