3

私はアクティブレコードベースのモデルを持っています:-ハウス

さまざまな属性がありますが、formal_name属性はありません。しかし、それはのための方法を持っていますformal_name、すなわち

def formal_name
    "Formal #{self.other_model.name}"
end

このメソッドが存在することをどのようにテストできますか?

私は持っています:

describe "check the name " do

    @report_set = FactoryGirl.create :report_set
    subject  { @report_set }
    its(:formal_name) { should == "this_should_fail"  }
end

しかし、私は得るundefined method 'formal_name' for nil:NilClass

4

2 に答える 2

3

まず、ファクトリがreport_setを適切に作成していることを確認する必要があります。おそらく、factory_girlをGemfileの開発グループとテストグループの両方に配置し、irbを起動してFactoryGirl.create :report_setnilが返されないことを確認します。

次に、試してください

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
于 2012-07-12T17:01:24.647 に答える
1

個人的には、私はあなたが使用しているショートカットrspec構文のファンではありません。私はこのようにします

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

このように理解する方がはるかに簡単だと思います。


編集:Rails3.2プロジェクトでのFactoryGirl2.5の完全な動作例。これはテスト済みのコードです

# 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
于 2012-07-12T16:50:23.303 に答える