Kam*_*nek 3 ruby testing rspec ruby-on-rails
我想在许多 RSpec 共享示例中包含一种方法来覆盖默认上下文方法:
describe 'Links' do
describe EditLink do
it_behaves_like 'update association service', :link do
def create_association(params, user_symbol)
AddLink.new(user_symbol).(params)
end
end
end
describe DeleteLink do
it_behaves_like 'delete association service', :link do
def create_association(params, user_symbol)
AddLink.new(user_symbol).(params)
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
有没有什么方法可以将create_association其提取并传递到共享示例中,以便它将覆盖共享上下文中的默认方法,而无需创建这些do ... end块并在每个示例中复制粘贴此方法it_behaves_like?
您应该能够使用RSpec 辅助方法来完成此操作。
在某处添加具有提取方法的模块,例如。spec/support/helpers.rb:
module Helpers
def create_association(params, user_symbol)
AddLink.new(user_symbol).(params)
end
end
Run Code Online (Sandbox Code Playgroud)
确保这是必需的rails_helper.rb。spec/support通常,使用默认 RSpec 设置时需要以下任何内容。
需要配置 RSpec 以扩展与模块的共享示例组。这可以在配置部分完成rails_helper.rb:
RSpec.configure do |config|
config.extend Helpers
end
Run Code Online (Sandbox Code Playgroud)
然后可以从共享示例块中调用该方法:
it_behaves_like 'delete association service', :link do
create_association(params, user_symbol)
end
Run Code Online (Sandbox Code Playgroud)
该文档解释了将模块限制为特定组的其他选项。
要在正常示例(即在共享示例之外)中使用帮助程序,您需要include代替(或补充)extend:
RSpec.configure do |config|
config.include Helpers
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5190 次 |
| 最近记录: |