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

有帮助吗?

解决方案

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

其他提示

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.


EDIT: Full working example with FactoryGirl 2.5 in a Rails 3.2 project. This is tested code

# 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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top