내가로드 할 때 script/console
때로는 컨트롤러의 출력 또는 뷰 도우미 메소드로 놀고 싶습니다.
다음과 같은 방법이 있습니까?
- 요청을 시뮬레이션?
- 상기 요청에 따라 컨트롤러 인스턴스로부터 메소드를 호출 하는가?
- 상기 컨트롤러 인스턴스 또는 다른 방법을 통해 도우미 메소드를 테스트합니까?
답변
헬퍼를 호출하려면 다음 helper
객체를 사용하십시오 .
$ ./script/console
>> helper.number_to_currency('123.45')
=> "R$ 123,45"
당신이 (당신이 제거하기 때문에, 말하자면 기본적으로 포함 아니에요 도우미 사용하려면 helper :all
에서를 ApplicationController
) 그냥 도우미를 포함한다.
>> include BogusHelper
>> helper.bogus
=> "bogus output"
컨트롤러 를 다루는 것에 관해서는 Nick의 대답을 인용합니다 .
> app.get '/posts/1' > response = app.response # you now have a rails response object much like the integration tests > response.body # get you the HTML > response.cookies # hash of the cookies # etc, etc
답변
스크립트 / 콘솔에서 컨트롤러 작업을 호출하고 응답 개체를보고 조작하는 쉬운 방법은 다음과 같습니다.
> app.get '/posts/1'
> response = app.response
# You now have a Ruby on Rails response object much like the integration tests
> response.body # Get you the HTML
> response.cookies # Hash of the cookies
# etc., etc.
앱 객체는 ActionController :: Integration :: Session 의 인스턴스입니다.
이것은 Ruby on Rails 2.1 및 2.3을 사용하여 작동하며 이전 버전을 시도하지 않았습니다.
답변
콘솔에서 테스트해야하는 경우 (Ruby on Rails 3.1 및 4.1에서 테스트) :
통화 컨트롤러 작업 :
app.get '/'
app.response
app.response.headers # => { "Content-Type"=>"text/html", ... }
app.response.body # => "<!DOCTYPE html>\n<html>\n\n<head>\n..."
ApplicationController 메소드 :
foo = ActionController::Base::ApplicationController.new
foo.public_methods(true||false).sort
foo.some_method
경로 도우미 :
app.myresource_path # => "/myresource"
app.myresource_url # => "http://www.example.com/myresource"
헬퍼보기 :
foo = ActionView::Base.new
foo.javascript_include_tag 'myscript' #=> "<script src=\"/javascripts/myscript.js\"></script>"
helper.link_to "foo", "bar" #=> "<a href=\"bar\">foo</a>"
ActionController::Base.helpers.image_tag('logo.png') #=> "<img alt=\"Logo\" src=\"/images/logo.png\" />"
세우다:
views = Rails::Application::Configuration.new(Rails.root).paths["app/views"]
views_helper = ActionView::Base.new views
views_helper.render 'myview/mytemplate'
views_helper.render file: 'myview/_mypartial', locals: {my_var: "display:block;"}
views_helper.assets_prefix #=> '/assets'
ActiveSupport 방법 :
require 'active_support/all'
1.week.ago
=> 2013-08-31 10:07:26 -0300
a = {'a'=>123}
a.symbolize_keys
=> {:a=>123}
라이브러리 모듈 :
> require 'my_utils'
=> true
> include MyUtils
=> Object
> MyUtils.say "hi"
evaluate: hi
=> true
답변
콘솔을 통해이를 수행하는 한 가지 방법이 있습니다.
>> foo = ActionView::Base.new
=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>
>> foo.extend YourHelperModule
=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>
>> foo.your_helper_method(args)
=> "<html>created by your helper</html>"
새 인스턴스를 만들면 ActionView::Base
도우미가 사용할 가능성이있는 일반적인보기 메서드에 액세스 할 수 있습니다. 그런 다음 확장하면 YourHelperModule
해당 메소드를 객체에 혼합하여 반환 값을 볼 수 있습니다.
답변
방법이 POST
방법 인 경우 :
app.post 'controller/action?parameter1=value1¶meter2=value2'
(여기의 매개 변수는 적용 가능성에 따라 다릅니다.)
그렇지 않은 경우 GET
방법 :
app.get 'controller/action'
답변
이를 수행하는 다른 방법은 Ruby on Rails 디버거를 사용하는 것입니다. http://guides.rubyonrails.org/debugging_rails_applications.html 에 디버깅에 관한 Ruby on Rails 가이드가 있습니다.
기본적으로 -u 옵션을 사용하여 서버를 시작하십시오.
./script/server -u
그런 다음 컨트롤러, 도우미 등에 액세스하려는 스크립트에 중단 점을 삽입하십시오.
class EventsController < ApplicationController
def index
debugger
end
end
그리고 요청을하고 코드에서 해당 부분을 누르면 서버 콘솔은 명령 프롬프트에서 요청을하고 개체를 볼 수있는 프롬프트를 반환합니다. 완료되면 ‘cont’을 입력하여 실행을 계속하십시오. 확장 된 디버깅 옵션도 있지만 최소한 시작해야합니다.
답변
다음은 Refinery를 예로 사용하여 인증 된 POST 요청을 작성하는 방법입니다.
# Start Rails console
rails console
# Get the login form
app.get '/community_members/sign_in'
# View the session
app.session.to_hash
# Copy the CSRF token "_csrf_token" and place it in the login request.
# Log in from the console to create a session
app.post '/community_members/login', {"authenticity_token"=>"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=", "refinery_user[login]"=>'chloe', 'refinery_user[password]'=>'test'}
# View the session to verify CSRF token is the same
app.session.to_hash
# Copy the CSRF token "_csrf_token" and place it in the request. It's best to edit this in Notepad++
app.post '/refinery/blog/posts', {"authenticity_token"=>"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=", "switch_locale"=>"en", "post"=>{"title"=>"Test", "homepage"=>"0", "featured"=>"0", "magazine"=>"0", "refinery_category_ids"=>["1282"], "body"=>"Tests do a body good.", "custom_teaser"=>"", "draft"=>"0", "tag_list"=>"", "published_at(1i)"=>"2014", "published_at(2i)"=>"5", "published_at(3i)"=>"27", "published_at(4i)"=>"21", "published_at(5i)"=>"20", "custom_url"=>"", "source_url_title"=>"", "source_url"=>"", "user_id"=>"56", "browser_title"=>"", "meta_description"=>""}, "continue_editing"=>"false", "locale"=>:en}
오류가 발생하면 다음과 같은 유용한 정보를 얻을 수 있습니다.
app.cookies.to_hash
app.flash.to_hash
app.response # long, raw, HTML
