1

州のモデルの rspec テストを作成しようとしています。この州モデルは、国モデルに関連付けられています。私の工場は次のようになります

Factory.define :country do |country|
  country.name  "Test Country"
end

Factory.define :state do |state|
  state.name "Test State"
  state.association :country
end

機能状態モデル rspec を作成しましたが、状態 @attr を設定する方法が正しいのかハックなのかわかりません

require 'spec_helper'

describe State do
  before(:each) do
    country = Factory(:country)
    @attr = { :name => 'Test State', :country_id => country.id }
  end

  it "should create a new state given valid attributes" do
    State.create!(@attr)
  end  
end

rails/rspec を初めて使用するので、強制的に言うこと:country_id => country.idが正しいのか、それとも問題を解決する安価な方法なのかわかりません。私が得ることができる助けや提案に感謝します。

念のため、両方のモデルも含めます。

class Country < ActiveRecord::Base
  has_many :states
  attr_accessible :name

  validates :name,  :presence => true,
                    :uniqueness => {:case_sensitive => false}
end

class State < ActiveRecord::Base
  belongs_to :country

  attr_accessible :name, :country_id

  validates :name,  :presence => true,
                    :uniqueness => {:case_sensitive => false, :scope => :country_id}

  validates :country_id, :presence => true
end
4

1 に答える 1

2

これは良いスタートですが、テストは実際には何もテストしていません。原則として、"it" ブロックごとに常に 1 つの "should" 呼び出しを行う必要があります。

同じ工場とモデルを想定した別の見方を次に示します。

require 'spec_helper'

describe State do
  before(:each) do
    @state = Factory.build(:state)
  end

  it "should create a new state given valid attributes" do
    @state.save.should be_true
  end
end
于 2010-10-20T00:08:46.760 に答える