美文网首页
rspec(2) - model

rspec(2) - model

作者: auguszou | 来源:发表于2016-10-29 23:08 被阅读0次

    没有测试的代码就是耍流氓

    1. rspec(1) - summary
    2. specs(2) - model
    3. specs(3) - controller
    4. specs(4) - request
    5. specs(5) - mock
    6. [specs(6) - mailer]
    7. [specs(7) - view]
    8. [specs(8) - routing]
    9. [specs(9) - helper]
    10. [specs(10) - factory-girl]
    11. [specs(11) - fake other gems]
    12. [specs(12) - sidekiq]
    13. [specs(13) - db migration]
    14. [specs(14) - timecop]
    15. [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 
    

    相关文章

      网友评论

          本文标题:rspec(2) - model

          本文链接:https://www.haomeiwen.com/subject/uwiyuttx.html