Tef*_*Ted 34 javascript ruby-on-rails response functional-testing
如果您的控制器操作如下所示:
respond_to do |format|
format.html { raise 'Unsupported' }
format.js # index.js.erb
end
Run Code Online (Sandbox Code Playgroud)
你的功能测试看起来像这样:
test "javascript response..." do
get :index
end
Run Code Online (Sandbox Code Playgroud)
它将执行respond_to块的HTML分支.
如果你试试这个:
test "javascript response..." do
get 'index.js'
end
Run Code Online (Sandbox Code Playgroud)
它执行视图(index.js.erb)而没有运行控制器动作!
Ale*_*yne 60
通过在:format你的正常PARAMS触发该格式的响应.
get :index, :format => 'js'
Run Code Online (Sandbox Code Playgroud)
无需弄乱您的请求标头.
Ste*_*oka 25
与rspec:
it "should render js" do
xhr :get, 'index'
response.content_type.should == Mime::JS
end
Run Code Online (Sandbox Code Playgroud)
并在您的控制器操作中:
respond_to do |format|
format.js
end
Run Code Online (Sandbox Code Playgroud)
将接受的内容类型设置为您想要的类型:
@request.accept = "text/javascript"
Run Code Online (Sandbox Code Playgroud)
将此与您的get :index测试相结合,它将对控制器进行适当的调用.
RSpec 3.7 and Rails 5.x solution:
A few of these answers were a little outdated in my case so I decided to provide an answer for those running Rails 5 and RSpec 3.7:
it "should render js" do
get :index, xhr: true
expect(response.content_type).to eq('text/javascript')
end
Run Code Online (Sandbox Code Playgroud)
Very similar to Steve's answer with a few adjustments. The first being xhr is passed as a boolean key/pair. Second is I now use expect due to should receiving deprecation warnings if used. Comparing the content_type of the response to be equal to text/javascript worked for me.