我正在尝试为国家模型创建一个 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