有一个私有方法,代码如下。
attr_reader :some_variable
validate :some_def
def some_def
unless some_variable.valid?
some_variable.errors.messages.each do |message|
errors.add(:some_variable, message)
end
end
我是rspec的新手,不熟悉私有方法测试。任何帮助表示赞赏。
我需要介绍私有方法的内容。
你可以这样做:
describe 'validations' do
let(:some_variable_object) { SomeVariable.new }
let(:new_foo) { described_class.new(some_variable: some_variable_object) }
context 'when some_variable is valid' do
before do
allow(some_variable_object).to receive(:valid?) { true }
end
it 'is valid' do
expect(new_foo).to be_valid
end
it 'does not have errors related to some_variable' do
expect(new_foo.errors[:some_variables]).to be_empty
end
end
那么当some_variable
无效时你可以做同样的事情来测试相反的...现在,有一些工具可以帮助你轻松地在规范中设置对象(FactoryBot)。