1

我正在尝试为国家模型创建一个 rspec 测试。此状态模型与 Country 模型有关联。我的工厂看起来像

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 的方式是正确的还是 hack

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”块都应该有一个“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 回答