没有测试的代码就是耍流氓
- rspec(1) - summary
- specs(2) - model
- specs(3) - controller
- specs(4) - request
- specs(5) - mock
- [specs(6) - mailer]
- [specs(7) - view]
- [specs(8) - routing]
- [specs(9) - helper]
- [specs(10) - factory-girl]
- [specs(11) - fake other gems]
- [specs(12) - sidekiq]
- [specs(13) - db migration]
- [specs(14) - timecop]
- [specs(15) - jenkins]
models specs
models的测试默认位于spec/models目录,任何设置:type => :model 当将被当做model specs代码。
创建User模型
rails generate model user name:string sex:integer age:integer
生成model测试(以User为例)
rails generate rspec:model user
迁移
bundle exec rake db:migrate RAILS_ENV=test
# or rails db:mirate RAILS_ENV=test
create测试(spec/models/user_spec.rb)
require "rails_helper"
RSpec.describe User, :type => :model do
it "create" do
user = User.create!(:name=>"zouqilin", :sex=>1, :age=>26)
expect(User.first).to eq(user)
end
end
find测试
require "rails_helper"
RSpec.describe User, :type => :model do
before("find") do
@user = User.create!(:name=>"zouqilin", :sex=>1, :age=>26)
end
it "find a user" do
expect(User.find_by_name("zouqilin")).to eq(@user)
end
it "not found" do
expect(User.find_by_name("zou")).to eq(nil)
end
end
where测试
require "rails_helper"
RSpec.describe User, :type => :model do
before("find") do
@user = User.create!(:name=>"zouqilin", :sex=>1, :age=>26)
end
it "find a user" do
expect(User.where(name: "zouqilin")).to eq([@user])
end
it "not found" do
expect(User.where(name: "zou")).to eq([nil])
end
end
update测试
context "update" do
before("update") do
@user = User.create!(:name=>"zouqilin", :sex=>1, :age=>26)
end
it "update user age" do
@user.age = 18
@user.save
expect(User.find(@user.id).age).to eq(18)
end
end
destroy测试
context "delete" do
before("delete") do
@user = User.create!(:name=>"zouqilin", :sex=>1, :age=>26)
end
it "delete user" do
@user.destroy
expect(User.where(id: @user.id)).to eq([])
end
end
关联模型
rails new model post title:string content:text
网友评论