Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何测试合成对象的设置';使用RSpec的属性?_Ruby_Oop - Fatal编程技术网

Ruby 如何测试合成对象的设置';使用RSpec的属性?

Ruby 如何测试合成对象的设置';使用RSpec的属性?,ruby,oop,Ruby,Oop,例如,我在Rails应用程序中有两个类——Customer类和Card类。客户类由卡片类组成,即客户有一张卡片 然后我有一个Rails控制器,它定义了一个“do_something”操作,它将使用POST中传递的参数初始化Customer的一个新实例(该实例将在内部创建一个新的Card实例) 然后,卡的编号设置如下: class ShopController < ApplicationController def do_something customer = Cu

例如,我在Rails应用程序中有两个类——Customer类和Card类。客户类由卡片类组成,即客户有一张卡片

然后我有一个Rails控制器,它定义了一个“do_something”操作,它将使用POST中传递的参数初始化Customer的一个新实例(该实例将在内部创建一个新的Card实例)

然后,卡的编号设置如下:

class ShopController < ApplicationController
    def do_something
        customer = Customer.new params
        customer.card.number = params[:card_number]
        ...
    end
end

有什么想法吗?也许它不容易测试的事实是一种代码味道,也许我应该在Customer类上创建一个setter方法?

我确实认为您在错误的级别上测试它。如果您愿意在单独的语句中设置卡号,那么最好创建一个函数来帮助您进行设置

class Customer
  def self.new_with_card_number(params, number)
    customer = new(params)
    customer.card.number = number
    customer
  end
end

describe Customer do
  it 'creates a card with a number' do
    customer = described_class.new_with_card_number({}, '1234')
    customer.card.number.should == '1234'
  end
end
然后,您可以将控制器更改为:

class ShopController < ApplicationController
  def do_something
    customer = Customer.new_with_card_number(params, params[:card_number])
  end
end

然后,您只需将调用更改为
customer=customer.new(params)

我会将客户模型更改为添加
已接受的\u嵌套属性\u for:card
,并将控制器操作更改为

class ShopController
然后你的规格可以看起来像

描述ShopController所做的事情
描述“发布/做某事”做什么
它“设置卡的卡号”吗
post:do_something,:customer=>
{
:card_attributes=>{:card_number=>'1234'}
}
Customer.last.card.number.should==“1234”
终止
终止
终止
class ShopController < ApplicationController
  def do_something
    customer = Customer.new_with_card_number(params, params[:card_number])
  end
end
params[:customer][:card_attributes][:card_number]