[rspec-users] a better "should have valid associations"
Ashley Moran
work at ashleymoran.me.uk
Thu Mar 29 09:37:21 EDT 2007
On 29 Mar 2007, at 14:03, Craig Demyanovich wrote:
> Doing more than this feels like doing too much. However, I'm still a
> bit of a beginner when it comes to Rails. Am I specifying too little?
> Am I missing something?
That's a lot more concise than my version! I'm sure there are people
with more informed opinions, but to me your solution looks like it
depends a lot on the Rails implementation, so the specs would be
useless if you wanted to switch (or could switch) to Og, say.
My specs look like this:
context "A SiteVariable (associations)" do
setup do
# fixtures here, then make a variable...
@variable = SiteVariable.new(:name => "variable")
end
specify "should belong to SiteVariableCategory" do
@variable.site_variable_type = @type
@variable.should respond_to(:site_variable_category)
@variable.should respond_to(:site_variable_category=)
@variable.site_variable_category = @category
@variable.save!
variable = SiteVariable.find(@variable.id)
variable.site_variable_category.should == @category
end
specify "should have many SiteValues" do
@variable.site_variable_category = @category
@variable.site_variable_type = @type
site_value_1 = SiteStringValue.new(:string_value =>
"value_1", :site => @site)
site_value_2 = SiteStringValue.new(:string_value =>
"value_2", :site => @site)
@variable.should respond_to(:site_values)
@variable.site_values.should respond_to(:<<)
@variable.site_values << site_value_1
@variable.site_values << site_value_2
@variable.save.should == true
variable_reloaded = SiteVariable.find(@variable.id)
variable_reloaded.site_values.sort { |a, b| a.string_value <=>
b.string_value }.should == [ site_value_1, site_value_2 ]
end
end
It's ugly and long winded, but it tests the actual behaviour. I'm
sure somewhere between the two approaches there's an ideal solution.
Ashley
More information about the rspec-users
mailing list