ビューのspecで、ウマい書き方がワカンネェー
Product(name: string, description: text, height: float, width: float, depth: float)というモデルがあったとして。
で、それを扱うProductsControllerがあったとして。
で、ビューのspecを書くとして。
rspec_scaffoldで生成されたspecは、こうなる訳だが。
# spec/products/show.html.erb_spec.rb require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "/products/show.html.erb" do include ProductsHelper before(:each) do assigns[:product] = @product = stub_model(Product, :name => "value for name", :description => "value for description", :height => 1.5, :width => 1.5, :depth => 1.5 ) end it "should render attributes in <p>" do render "/mogos/show.html.erb" response.should have_text(/value\ for\ name/) response.should have_text(/value\ for\ description/) response.should have_text(/1\.5/) response.should have_text(/1\.5/) response.should have_text(/1\.5/) end end
ああ、イヤ、待たれい待たれい。
response.should have_text(某)って、それ、一つでもマッチしないと、failure返ってくるよね?
そうじゃなくって、ひとつの属性ごとに、example書きたいじゃない?
でも、
it "なんちゃらー" do response.should have_text(/なんちゃらー/) end
なんて、何度も書きたくないよねぇ。
で。
describe "ほにゃららー" do @product2 = Product.new({ :name => "value for name", :description => "value for description", :height => 1.5, :width => 1.5, :depth => 1.5 }) @product2.attributes.each do |key, value| it "#{key}" do responce.should have_text(/#{value}/) end end end
とかすれば、まあ、事足りるっちゃあ、事足りるんだけど。
でも、どうせなら、stubとやら、使ってみたいじゃない?
んで、こんな風に、
describe "よろれいひー" do @product.attributes.each do |key, value| # @productは、stub_model(Product) it "#{key}" do responce.should have_text(/#{value}/) end end end
書くと、これが、
# => You have a nil object when you didn't expect it! (NoMethodError) You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.attributes from ~
って怒られる訳さ。
そりゃそうだ。
@productって、it~が始まる直前でないと、作られないもんね。
でも、@productの定義を、beforeの外でやろうとすると、
undefined local variable or method `stub_product' for Spec::Rails::Example::ViewExampleGroup::Subclass_1:Class (NameError) from ~
って怒られちゃうんだな...
さて。
どうしたものでしょう...