rspec-rails readme
2017-08-07 11:44
393 查看
rspec-rails is a testing framework for Rails 3.x, 4.x and 5.0.
Use rspec-rails 1.x for Rails 2.x.
Want to run against the
to your
Download and install by running:
Initialize the
This adds the following files which are used for configuration:
Check the comments in each file for more information.
Use the
By default the above will run all
For more details about this see the RSpec spec file docs.
To run only a subset of these specs use the following command:
Specs can also be run via
In Rails 4, you may want to create a binstub for the
For detailed information on the general RSpec 3.x upgrade process see the RSpec Upgrade docs.
There are three particular
The default helper files created in RSpec 3.x have changed
File-type inference disabled by default
Rails 4.x
migration checks
Extraction of
In Rails 5.x, controller testing has been moved to its own gem which is rails-controller-testing.
Using
the conventional RSpec configuration helper, whilst the Rails specific loading and bootstrapping has moved to the
Rails specs now need this file required beforehand either at the top of the specific file (recommended) or a common configuration location such as your
Please see the RSpec Rails Upgrade docs for full details.
NOTE: Generators run in RSpec 3.x will now require
of
Once installed, RSpec will generate spec files instead of Test::Unit test files when commands like
You may also invoke RSpec generators independently. For instance, running
a model spec. For more information, see list of all generators.
Once you've set up the environment, you'll need to cd into the working directory of whichever repo you want to work in. From there you can run the specs and cucumber features, and make patches.
NOTE: You do not need to use rspec-dev to work on a specific RSpec repo. You can treat each RSpec repo as an independent project. Please see the following files:
For
Build details
Code of Conduct
Detailed contributing guide
Development setup guide
Use model specs to describe behavior of models (usually ActiveRecord-based) in the application.
Model specs default to residing in the
For example:
For more information, see cucumber scenarios for model specs.
Use controller specs to describe behavior of Rails controllers.
Controller specs default to residing in the
For example:
For more information, see cucumber scenarios for controller specs.
Note: To encourage more isolated testing, views are not rendered by default in controller specs. If you are verifying discrete view logic, use a view
spec. If you are verifying the behaviour of a controller and view together, consider a request spec. You can use render_views if
you must verify the rendered view contents within a controller spec, but this is not recommended.
Use request specs to specify one or more request/response cycles from end to end using a black box approach.
Request specs default to residing in the
and
Request specs mix in behavior from ActionDispatch::Integration::Runner, which is the basis for Rails'
integration tests.
The above example uses only standard Rails and RSpec APIs, but many RSpec/Rails users like to use extension libraries likeFactoryGirl and Capybara:
FactoryGirl decouples this example from changes to validation requirements, which can be encoded into the underlying factory definition without requiring changes to this example.
Among other benefits, Capybara binds the form post to the generated HTML, which means we don't need to specify them separately. Note that Capybara's DSL as shown is, by default, only available in specs in the spec/features directory. For more information, see
the Capybara integration docs.
There are several other Ruby libs that implement the factory pattern or provide a DSL for request specs (a.k.a. acceptance or integration specs), but FactoryGirl and Capybara seem to be the most widely used. Whether you choose these or other libs, we strongly
recommend using something for each of these roles.
Feature specs test your application from the outside by simulating a browser.
used to manage the simulated browser.
Feature specs default to residing in the
Feature specs mix in functionality from the capybara gem, thus they require
add
For more information, see the cucumber scenarios for feature specs.
By default Mailer specs reside in the
For more information, see the cucumber scenarios for mailer specs .
Tagging a context with the metadata
live in
For more information, see the cucumber scenarios for job specs .
View specs default to residing in the
View specs mix in
View specs infer the controller name and path from the path to the view template. e.g. if the template is
This means that most of the time you don't need to set these values. When spec'ing a partial that is included across different controllers, you may need to override these values before rendering the view.
To provide a layout for the render, you'll need to specify both the template and the layout explicitly. For example:
Use this to assign values to instance variables in the view:
The code above assigns
in the view, and then renders the view.
Note that because view specs mix in
propagated into your views (similar to how instance variables you set in controller actions are made available in views). For example:
RSpec doesn't officially support this pattern, which only works as a side-effect of the inclusion of
Be aware that it may be made unavailable in the future.
This represents the rendered view.
Routing specs default to residing in the
Helper specs default to residing in the
Helper specs mix in ActionView::TestCase::Behavior. A
being spec'd, along with
Several domain-specific matchers are provided to each of the example group types. Most simply delegate to their equivalent Rails' assertions.
Available in all specs
Primarily intended for controller specs
Passes if the object is a
Delegates to Rails'
Available in request, controller, and view specs
In request and controller specs, apply to the
In view specs, apply to the
Delegates to
Available in request and controller specs
Delegates to Rails'
Available in routing and controller specs
Passes if the path is recognized by Rails' routing. This is primarily intended to be used with
standard CRUD routes which should not be routable.
Passes if
The following symbolic status codes are allowed:
One of the defined
Available in controller, feature, and request specs.
In controller and request specs, apply to the
In feature specs, apply to the
Several rake tasks are provided as a convenience for working with RSpec. To run the entire spec suite use
To run a subset of specs use the associated type task, for example
A full list of the available rake tasks can be seen by running
If you want to customize the behavior of
your own task in the
defined:
https://github.com/rspec/rspec
https://github.com/rspec/rspec-core
https://github.com/rspec/rspec-expectations
https://github.com/rspec/rspec-mocks
See http://github.com/rspec/rspec-rails/issues
Use rspec-rails 1.x for Rails 2.x.
安装
在Gimefile中给:development
and :test group添加
rspec-rails
group :development, :test do gem 'rspec-rails', '~> 3.5' end
Want to run against the
masterbranch? You'll need to include the dependent RSpec repos as well. Add the following
to your
Gemfile:
%w[rspec-core rspec-expectations rspec-mocks rspec-rails rspec-support].each do |lib| gem lib, :git => "https://github.com/rspec/#{lib}.git", :branch => 'master' end
Download and install by running:
bundle install
Initialize the
spec/directory (where specs will reside) with:
rails generate rspec:install
This adds the following files which are used for configuration:
.rspec
spec/spec_helper.rb
spec/rails_helper.rb
Check the comments in each file for more information.
Use the
rspeccommand to run your specs:
bundle exec rspec
By default the above will run all
_spec.rbfiles in the
specdirectory.
For more details about this see the RSpec spec file docs.
To run only a subset of these specs use the following command:
# Run only model specs bundle exec rspec spec/models # Run only specs for AccountsController bundle exec rspec spec/controllers/accounts_controller_spec.rb # Run only spec on line 8 of AccountsController bundle exec rspec spec/controllers/accounts_controller_spec.rb:8
Specs can also be run via
rake spec, though this command may be slower to start than the
rspeccommand.
In Rails 4, you may want to create a binstub for the
rspeccommand so it can be run via
bin/rspec:
bundle binstubs rspec-core
Upgrade
Note
For detailed information on the general RSpec 3.x upgrade process see the RSpec Upgrade docs.There are three particular
rspec-railsspecific changes to be aware of:
The default helper files created in RSpec 3.x have changed
File-type inference disabled by default
Rails 4.x
ActiveRecord::Migrationpending
migration checks
Extraction of
stub_modeland
mock_modelto
rspec-activemodel-mocks
In Rails 5.x, controller testing has been moved to its own gem which is rails-controller-testing.
Using
assignsin your controller specs without adding this gem will no longer work.
rspec-railsnow includes two helpers,
spec_helper.rband
rails_helper.rb.
spec_helper.rbis
the conventional RSpec configuration helper, whilst the Rails specific loading and bootstrapping has moved to the
rails_helper.rbfile.
Rails specs now need this file required beforehand either at the top of the specific file (recommended) or a common configuration location such as your
.rspecfile.
Please see the RSpec Rails Upgrade docs for full details.
NOTE: Generators run in RSpec 3.x will now require
rails_helperinstead
of
spec_helper.
Generators
Once installed, RSpec will generate spec files instead of Test::Unit test files when commands like rails generate modeland
rails generate controllerare used.
You may also invoke RSpec generators independently. For instance, running
rails generate rspec:modelwill generate
a model spec. For more information, see list of all generators.
Contributing
Once you've set up the environment, you'll need to cd into the working directory of whichever repo you want to work in. From there you can run the specs and cucumber features, and make patches.NOTE: You do not need to use rspec-dev to work on a specific RSpec repo. You can treat each RSpec repo as an independent project. Please see the following files:
For
rspec-rails-specific development information, see
Build details
Code of Conduct
Detailed contributing guide
Development setup guide
Model Specs
Use model specs to describe behavior of models (usually ActiveRecord-based) in the application.Model specs default to residing in the
spec/modelsfolder. Tagging any context with the metadata
:type => :modeltreats its examples as model specs.
For example:
require "rails_helper" RSpec.describe User, :type => :model do it "orders by last name" do lindeman = User.create!(first_name: "Andy", last_name: "Lindeman") chelimsky = User.create!(first_name: "David", last_name: "Chelimsky") expect(User.ordered_by_last_name).to eq([chelimsky, lindeman]) end end
For more information, see cucumber scenarios for model specs.
Controller
Specs
Use controller specs to describe behavior of Rails controllers.Controller specs default to residing in the
spec/controllersfolder. Tagging any context with the metadata
:type => :controllertreats its examples as controller specs.
For example:
require "rails_helper" RSpec.describe PostsController, :type => :controller do describe "GET #index" do it "responds successfully with an HTTP 200 status code" do get :index expect(response).to be_success expect(response).to have_http_status(200) end it "renders the index template" do get :index expect(response).to render_template("index") end it "loads all of the posts into @posts" do post1, post2 = Post.create!, Post.create! get :index expect(assigns(:posts)).to match_array([post1, post2]) end end end
For more information, see cucumber scenarios for controller specs.
Note: To encourage more isolated testing, views are not rendered by default in controller specs. If you are verifying discrete view logic, use a view
spec. If you are verifying the behaviour of a controller and view together, consider a request spec. You can use render_views if
you must verify the rendered view contents within a controller spec, but this is not recommended.
Request
Specs
Use request specs to specify one or more request/response cycles from end to end using a black box approach.Request specs default to residing in the
spec/requests,
spec/api,
and
spec/integrationdirectories. Tagging any context with the metadata
:type => :requesttreats its examples as request specs.
Request specs mix in behavior from ActionDispatch::Integration::Runner, which is the basis for Rails'
integration tests.
require 'rails_helper' RSpec.describe "home page", :type => :request do it "displays the user's username after successful login" do user = User.create!(:username => "jdoe", :password => "secret") get "/login" assert_select "form.login" do assert_select "input[name=?]", "username" assert_select "input[name=?]", "password" assert_select "input[type=?]", "submit" end post "/login", :username => "jdoe", :password => "secret" assert_select ".header .username", :text => "jdoe" end end
The above example uses only standard Rails and RSpec APIs, but many RSpec/Rails users like to use extension libraries likeFactoryGirl and Capybara:
require 'rails_helper' RSpec.describe "home page", :type => :request do it "displays the user's username after successful login" do user = FactoryGirl.create(:user, :username => "jdoe", :password => "secret") visit "/login" fill_in "Username", :with => "jdoe" fill_in "Password", :with => "secret" click_button "Log in" expect(page).to have_selector(".header .username", :text => "jdoe") end end
FactoryGirl decouples this example from changes to validation requirements, which can be encoded into the underlying factory definition without requiring changes to this example.
Among other benefits, Capybara binds the form post to the generated HTML, which means we don't need to specify them separately. Note that Capybara's DSL as shown is, by default, only available in specs in the spec/features directory. For more information, see
the Capybara integration docs.
There are several other Ruby libs that implement the factory pattern or provide a DSL for request specs (a.k.a. acceptance or integration specs), but FactoryGirl and Capybara seem to be the most widely used. Whether you choose these or other libs, we strongly
recommend using something for each of these roles.
Feature
Specs
Feature specs test your application from the outside by simulating a browser. capybarais
used to manage the simulated browser.
Feature specs default to residing in the
spec/featuresfolder. Tagging any context with the metadata
:type => :featuretreats its examples as feature specs.
Feature specs mix in functionality from the capybara gem, thus they require
capybarato use. To use feature specs,
add
capybarato the
Gemfile:
gem "capybara"
For more information, see the cucumber scenarios for feature specs.
Mailer
specs
By default Mailer specs reside in the spec/mailersfolder. Adding the metadata
:type => :mailerto any context makes its examples be treated as mailer specs.
ActionMailer::TestCase::Behavioris mixed into your mailer specs.
require "rails_helper" RSpec.describe Notifications, :type => :mailer do describe "notify" do let(:mail) { Notifications.signup } it "renders the headers" do expect(mail.subject).to eq("Signup") expect(mail.to).to eq(["to@example.org"]) expect(mail.from).to eq(["from@example.com"]) end it "renders the body" do expect(mail.body.encoded).to match("Hi") end end end
For more information, see the cucumber scenarios for mailer specs .
Job specs
Tagging a context with the metadata :type => :jobtreats its examples as job specs. Typically these specs will
live in
spec/jobs.
require 'rails_helper' RSpec.describe UploadBackupsJob, :type => :job do describe "#perform_later" do it "uploads a backup" do ActiveJob::Base.queue_adapter = :test UploadBackupsJob.perform_later('backup') expect(UploadBackupsJob).to have_been_enqueued end end end
For more information, see the cucumber scenarios for job specs .
View specs
View specs default to residing in the spec/viewsfolder. Tagging any context with the metadata
:type => :viewtreats its examples as view specs.
View specs mix in
ActionView::TestCase::Behavior.
require 'rails_helper' RSpec.describe "events/index", :type => :view do it "renders _event partial for each event" do assign(:events, [double(Event), double(Event)]) render expect(view).to render_template(:partial => "_event", :count => 2) end end RSpec.describe "events/show", :type => :view do it "displays the event location" do assign(:event, Event.new(:location => "Chicago")) render expect(rendered).to include("Chicago") end end
View specs infer the controller name and path from the path to the view template. e.g. if the template is
events/index.html.erbthen:
controller.controller_path == "events" controller.request.path_parameters[:controller] == "events"
This means that most of the time you don't need to set these values. When spec'ing a partial that is included across different controllers, you may need to override these values before rendering the view.
To provide a layout for the render, you'll need to specify both the template and the layout explicitly. For example:
render :template => "events/show", :layout => "layouts/application"
assign(key,
val)
Use this to assign values to instance variables in the view:assign(:widget, Widget.new) render
The code above assigns
Widget.newto the
@widgetvariable
in the view, and then renders the view.
Note that because view specs mix in
ActionView::TestCasebehavior, any instance variables you set will be transparently
propagated into your views (similar to how instance variables you set in controller actions are made available in views). For example:
@widget = Widget.new render # @widget is available inside the view
RSpec doesn't officially support this pattern, which only works as a side-effect of the inclusion of
ActionView::TestCase.
Be aware that it may be made unavailable in the future.
Upgrade
note
# rspec-rails-1.x assigns[key] = value # rspec-rails-2.x+ assign(key, value)
rendered
This represents the rendered view.render expect(rendered).to match /Some text expected to appear on the page/
Upgrade
note
# rspec-rails-1.x render response.should xxx # rspec-rails-2.x+ render rendered.should xxx # rspec-rails-2.x+ with expect syntax render expect(rendered).to xxx
Routing
specs
Routing specs default to residing in the spec/routingfolder. Tagging any context with the metadata
:type => :routingtreats its examples as routing specs.
require 'rails_helper' RSpec.describe "routing to profiles", :type => :routing do it "routes /profile/:username to profile#show for username" do expect(:get => "/profiles/jsmith").to route_to( :controller => "profiles", :action => "show", :username => "jsmith" ) end it "does not expose a list of profiles" do expect(:get => "/profiles").not_to be_routable end end
Upgrade
note
route_forfrom rspec-rails-1.x is gone. Use
route_toand
be_routableinstead.
Helper
specs
Helper specs default to residing in the spec/helpersfolder. Tagging any context with the metadata
:type => :helpertreats its examples as helper specs.
Helper specs mix in ActionView::TestCase::Behavior. A
helperobject is provided which mixes in the helper module
being spec'd, along with
ApplicationHelper(if present).
require 'rails_helper' RSpec.describe EventsHelper, :type => :helper do describe "#link_to_event" do it "displays the title, and formatted date" do event = Event.new("Ruby Kaigi", Date.new(2010, 8, 27)) # helper is an instance of ActionView::Base configured with the # EventsHelper and all of Rails' built-in helpers expect(helper.link_to_event).to match /Ruby Kaigi, 27 Aug, 2010/ end end end
Matchers
Several domain-specific matchers are provided to each of the example group types. Most simply delegate to their equivalent Rails' assertions.
be_a_new
Available in all specsPrimarily intended for controller specs
expect(object).to be_a_new(Widget)
Passes if the object is a
Widgetand returns true for
new_record?
render_template
Delegates to Rails' assert_template
Available in request, controller, and view specs
In request and controller specs, apply to the
responseobject:
expect(response).to render_template("new")
In view specs, apply to the
viewobject:
expect(view).to render_template(:partial => "_form", :locals => { :widget => widget } )
redirect_to
Delegates to assert_redirect
Available in request and controller specs
expect(response).to redirect_to(widgets_path)
route_to
Delegates to Rails' assert_routing
Available in routing and controller specs
expect(:get => "/widgets").to route_to(:controller => "widgets", :action => "index")
be_routable
Passes if the path is recognized by Rails' routing. This is primarily intended to be used with not_toto specify
standard CRUD routes which should not be routable.
expect(:get => "/widgets/1/edit").not_to be_routable
have_http_status
Passes if responsehas a matching HTTP status code
The following symbolic status codes are allowed:
Rack::Utils::SYMBOL_TO_STATUS_CODE
One of the defined
ActionDispatch::TestResponsealiases:
:error
:missing
:redirect
:success
Available in controller, feature, and request specs.
In controller and request specs, apply to the
responseobject:
expect(response).to have_http_status(201) expect(response).not_to have_http_status(:created)
In feature specs, apply to the
pageobject:
expect(page).to have_http_status(:success)
rake
tasks
Several rake tasks are provided as a convenience for working with RSpec. To run the entire spec suite use rake spec.
To run a subset of specs use the associated type task, for example
rake spec:models.
A full list of the available rake tasks can be seen by running
rake -T | grep spec.
Customizing rake
tasks
If you want to customize the behavior of rake spec, you may define
your own task in the
Rakefilefor your project. However, you must first clear the task that rspec-rails
defined:
task("spec").clear
Also see
https://github.com/rspec/rspechttps://github.com/rspec/rspec-core
https://github.com/rspec/rspec-expectations
https://github.com/rspec/rspec-mocks
Feature
Requests & Bugs
See http://github.com/rspec/rspec-rails/issues
相关文章推荐
- 使用Rspec进行rails测试详解1-搭建测试环境
- Rails 3.2.3 使用 Spork + Guard + RSpec + Capybara + livereload
- MongoDB README
- rails generate rspec:install后测试框架生成规律
- file /usr/share/mysql/charsets/README from install
- php mail class with readme
- ruby on rails中使用 RSpec 进行行为驱动测试
- CJL.0.1.min.js readme
- Writing a good README
- OBS readme
- Rails中rspec测试xxx_path调用失败的解决
- Rails 之微信开发 : OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
- linux kernel README
- Rspec在Rails项目中的使用
- Red5 Plugin Readme
- Rails中rspec测试xxx_path调用失败的解决
- 使用Rspec进行rails测试详解1-Transactions
- LoRDEC 0.5 - README file
- VideoCenter App's README
- file /usr/share/mysql/charsets/README from install of MySQL-server-5.1.73-1.glibc23.i386 conflicts with file from package mysql-libs-5.1.73-8.el6_8.i686