我有一个用于动态映射属性的rails应用程序。此方法在创建操作期间运行。出于某种原因,我的Rspec示例将通过,但我的Cucumber场景现在失败,因为我已经实现了这个方法。
class Product < ActiveRecord::Base
def method_missing(method, *args)
if method.to_s['=']
self.define_singleton_method(method) do |*args|
self.instance_variable_set("@#{method[0..-2]}", args.first)
end
else
self.define_singleton_method(method) do
self.instance_variable_get("@#{method}")
end
end
self.send(method, *args) rescue super
end
def map_features
@features = {}
singleton_methods.each do |m|
m = m.to_s.chomp('=')
unless m == "brand" || m == "model"
@features[m] = self.send(m)
end
end
@features
end
end
产品控制器:
class ProductsController < ApplicationController
def index
@products = Product.all
end
def new
@product = Product.new
end
def create
@product = Product.new
if map_features && @product.save!
flash[:notice] = "Success: Your product was saved!"
else
flash[:notice] = "Failure"
end
redirect_to @product
end
def show
@product = Product.last
end
end
失败的黄瓜步骤:
When(/^I upload the product with a "(.*?)" inch screen$/) do |screen_size|
visit new_product_path
fill_in('Brand', :with => @product.brand)
fill_in('Model', :with => @product.model)
fill_in('Screen Size', :with => screen_size)
click_button 'Submit Product'
page.should have_content("Success: Your product was saved!")
end
传递 Rspec示例:
describe ProductsController do
describe "listing an item" do
context "params with only brand and model" do
it "creates an item without features" do
params = {:brand => "Dell", :model => "N5050"}
product = FactoryGirl.build(:product, params)
product.map_features
product.brand.should eq("Dell")
end
end
context "params with brand, model, and 1 feature" do
it "creates an item with 1 feature" do
params = {:brand => "Dell", :model => "N5050", :screen => "15", :port => "usb"}
product = FactoryGirl.build(:product, params)
product.map_features
product.features["screen"].should eq("15")
end
end
end
我收到的错误是:
undefined local variable or method `map_features' for #<ProductsController:0x0000000234d800> (NameError)
./app/controllers/products_controller.rb:24:in `create'
./features/step_definitions/new_product_steps.rb:12:in `/^I upload the product with a "(.*?)" inch screen$/'
features/new_product.feature:9:in `When I upload the product with a "15" inch screen'