作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用 RSpec 测试以下代码的最佳方法是什么?我应该测试什么? show 操作打开一个文件并流式传输它。此外,如果该操作依赖于某处存在的文件,我可以对其进行测试吗?
def show
image_option = params[:image_option]
respond_to do |format|
format.js
format.pdf {open_bmap_file("#{@bmap.bmap_pdf_file}", 'application/pdf', "#{@bmap.bmap_name}.pdf", "pdf", "pdf")}
format.png {open_bmap_file("#{@bmap.bmap_png_file}", 'image/png', "#{@bmap.bmap_name}.png", "png", image_option)}
end
end
private
def open_bmap_file(filename, application_type, send_filename, format, image_option = nil)
filename = "app/assets/images/image_not_available_small.png" unless File.exist? filename
path = Bmap.bmaps_pngs_path
case image_option
when "image"
filename = "#{@bmap.bmap_name}.png"
when "large_thumbnail"
filename = "#{@bmap.bmap_name}_large_thumb.png"
when "thumbnail"
filename = "#{@bmap.bmap_name}_thumb.png"
when "pdf"
filename = "#{@bmap.bmap_name}.pdf"
path = Bmap.bmaps_pdfs_path
else
filename = "#{@bmap.bmap_name}.pdf"
path = Bmap.bmaps_pdfs_path
end
begin
File.open(path + filename, 'rb') do |f|
send_data f.read, :disposition => image_option == "pdf" ? 'attachment' : 'inline', :type => application_type, :filename => send_filename
end
rescue
flash[:error] = 'File not found.'
redirect_to root_url
end
最佳答案
我需要测试 send_data
在下载 csv 文件的 Controller 操作中,我按照以下方式进行了操作。
Controller :
def index
respond_to do |format|
format.csv do
send_data(Model.generate_csv,
type: 'text/csv; charset=utf-8; header=present',
filename: "report.csv",
disposition: 'attachment')
end
end
end
context "when format is csv" do
let(:csv_string) { Model.generate_csv }
let(:csv_options) { {filename: "report.csv", disposition: 'attachment', type: 'text/csv; charset=utf-8; header=present'} }
it "should return a csv attachment" do
@controller.should_receive(:send_data).with(csv_string, csv_options).
and_return { @controller.render nothing: true } # to prevent a 'missing template' error
get :index, format: :csv
end
end
context "when format is csv" do
let(:csv_string) { Model.generate_csv }
let(:csv_options) { {filename: "report.csv", disposition: 'attachment', type: 'text/csv; charset=utf-8; header=present'} }
it "should return a csv attachment" do
expect(@controller).to receive(:send_data).with(csv_string, csv_options) {
@controller.render nothing: true # to prevent a 'missing template' error
}
get :index, format: :csv
end
end
关于ruby-on-rails - 如何在 RSpec 中测试 send_data?或者……在这种情况下我应该测试什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10357563/
我是一名优秀的程序员,十分优秀!