Ruby on rails 添加'后测试失败;属于';在Rails应用程序中建模
在Rails中将“”添加到“”后测试失败 我在Rails应用程序中有两种型号:Ruby on rails 添加'后测试失败;属于';在Rails应用程序中建模,ruby-on-rails,testing,Ruby On Rails,Testing,在Rails中将“”添加到“”后测试失败 我在Rails应用程序中有两种型号: class Micropost < ApplicationRecord belongs_to :user # Test failed after add this string validates :content, length: { maximum: 140 }, presence: true end class User < ApplicationRecord has_many :mi
class Micropost < ApplicationRecord
belongs_to :user # Test failed after add this string
validates :content, length: { maximum: 140 }, presence: true
end
class User < ApplicationRecord
has_many :microposts
validates :name, presence: true
validates :email, presence: true
end
我有一个控制器“MicropostsController”:
固定装置微孔:
one:
content: MyText
user_id: 1
two:
content: MyText
user_id: 1
如何改进这些测试以通过?方法还为用户添加了状态验证。在rails代码的某个地方,它添加了如下内容:
验证:用户的存在
并检查用户是否存在。在装置中,您已设置用户id:1
。但是在您的测试中,没有ID为1的用户。要修复它,您必须为您的microposts装置设置正确的用户ID
你可以用下面的方法来做。您不必定义用户id
,您可以在装置中定义关联:
one:
content: MyText
user: one
two:
content: MyText
user: one
定义一个user
键,而不是user\u id
,并使用用户装置中的装置名称作为值-在测试中,如果您想访问此装置,它将被称为users(:one)
注意:您也可以通过将必需:false
添加到您的属于
定义中来删除状态验证,但我不建议这样做。您可以添加控制器代码以及在测试中定义了“@micropost”变量的代码吗?@edariedl我已经添加了一些关于测试的信息和一些控制器方法。I我想在microspostscontroller
和microsposts(:一)
@edariedl中看到另外两个东西microspost\u params
定义。
class MicropostsController < ApplicationController
before_action :set_micropost, only: [:show, :edit, :update, :destroy]
# POST /microposts
# POST /microposts.json
def create
@micropost = Micropost.new(micropost_params)
respond_to do |format|
if @micropost.save
format.html { redirect_to @micropost, notice: 'Micropost was successfully created.' }
format.json { render :show, status: :created, location: @micropost }
else
format.html { render :new }
format.json { render json: @micropost.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /microposts/1
# PATCH/PUT /microposts/1.json
def update
respond_to do |format|
if @micropost.update(micropost_params)
format.html { redirect_to @micropost, notice: 'Micropost was successfully updated.' }
format.json { render :show, status: :ok, location: @micropost }
else
format.html { render :edit }
format.json { render json: @micropost.errors, status: :unprocessable_entity }
end
end
end
class MicropostsControllerTest < ActionDispatch::IntegrationTest
setup do
@micropost = microposts(:one)
end
def micropost_params
params.require(:micropost).permit(:content, :user_id)
end
one:
content: MyText
user_id: 1
two:
content: MyText
user_id: 1
one:
content: MyText
user: one
two:
content: MyText
user: one