我是Ruby和Rspec的新手,所以我碰巧发现了这段代码:
这是我的规范:
RSpec.describe Surveyor::Answer, '03: Answer validations' do
context "for a free text question" do
let(:question) { double(Surveyor::Question, type: 'free_text') }
# NOTE: The rating validations should not apply for 'free_text' questions.
subject { described_class.new(question: question, value: 'anything') }
it { should be_valid }
end
这是我的班级:
module Surveyor
class Answer
def initialize(question_answer)
@question = question_answer[:question]
@answer = question_answer[:value]
end
def question_type
# I want to check what is the type of question here.
# 'free_text' or 'rating'
# if free_text
# print question type
# else
# do something
end
end
我的问题是如何在Answer类中打印(放置)问题类型(free_text / rating)?
当我尝试使用print question_answer[:question]
时,它只给了我#<Double Surveyor::Question>
所以我无法使用question_answer[:question][:type]
答案 0 :(得分:0)
您可以简单地访问构造函数中的类型:question_answer[:question].type
,或稍后使用对象级方法:@question.type
。
您无法像question_answer[:question][:type]
那样访问它,因为测试中的double
方法会创建类似对象的经典对象,而不是哈希。
提示:当方法接受参数作为单个哈希时,您只需将其命名为options
或params
,但如果只有3-4个参数,则可以使用单独的变量代替参数哈希