在Rails中添加belongs_to后,测试失败
我在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 :microposts
validates :name, presence: true
validates :email, presence: true
end我在模型"Micropost“中添加了字符串"belongs_to :user”。在那之后,我进行了测试,结果失败了:
rails test
1) Failure:
MicropostsControllerTest#test_should_create_micropost [/home/kiselev/project/toy_app/test/controllers/microposts_controller_test.rb:19]:
"Micropost.count" didn't change by 1.
Expected: 3
Actual: 2
2) Failure:
MicropostsControllerTest#test_should_update_micropost [/home/kiselev/project/toy_app/test/controllers/microposts_controller_test.rb:38]:
Expected response to be a <3XX: redirect>, but was a <200: OK>我做了两次测试:
test "should create micropost" do
assert_difference('Micropost.count') do
post microposts_url, params: { micropost: { content: @micropost.content, user_id: @micropost.user_id } }
end
assert_redirected_to micropost_url(Micropost.last)
end
test "should update micropost" do
patch micropost_url(@micropost), params: { micropost: { content: @micropost.content, user_id: @micropost.user_id } }
assert_redirected_to micropost_url(@micropost)
end我有一个控制器"MicropostsController":
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微站控制器中的Params:
def micropost_params
params.require(:micropost).permit(:content, :user_id)
end固定装置-微博:
one:
content: MyText
user_id: 1
two:
content: MyText
user_id: 1我如何改进这些考试才能通过?
发布于 2019-09-08 15:03:06
至方法还为user添加了一个存在验证。在rails代码中的某个地方,它添加了如下内容:
validates_presence_of :user并检查用户是否存在。在您的夹具中,您已经设置了user_id: 1。但是在您的测试中,没有一个以1作为ID的用户。要修复它,您必须为您的微型文章固定装置设置正确的用户ID。
你可以用以下的方式来做。您不必定义user_id,您可以在设备中定义关联:
one:
content: MyText
user: one
two:
content: MyText
user: one定义一个user键而不是user_id,并作为一个值使用来自用户夹具的夹具名称--在测试中,如果您想要访问这个夹具,它将被称为users(:one)。
注意:您也可以通过将required: false添加到belongs_to定义中来删除存在验证,但我不建议这样做。
https://stackoverflow.com/questions/57842607
复制相似问题