rspec 模型与 Factory Girl 的关联
我正在尝试为州模型创建 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
I am trying to create a rspec test for a model for States. This state model has an association to a Country model. My factories look like
Factory.define :country do |country|
country.name "Test Country"
end
Factory.define :state do |state|
state.name "Test State"
state.association :country
end
I have made a functional state model rspec but I am not sure if the way I set up the state @attr is correct or a 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
Being new to rails/rspec I'm unsure if forcibly saying :country_id => country.id
is correct or a cheap way of solving the issue. I appreciate any help or suggestions I can get.
I am also including both models just in case.
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个好的开始,但您的测试实际上并没有测试任何东西。作为一般规则,每个“it”块应该始终有一个“应该”调用。
这是另一种看待它的方式,假设相同的工厂和模型:
This is a good start, but your test isn't actually testing anything. As a general rule, you should always have one "should" call per "it" block.
Here's another way of looking at it, assuming the same factories and models: