这就是 Rails test:controllers 让我明白的。
Failure:
StoriesControllerTest#test_adds_a_story [test/controllers/stories_controller_test.rb:42]:
Expected response to be a redirect to <http://www.example.com/stories/980190962> but was a redirect to <http://www.example.com/stories/980190963>.
Expected "http://www.example.com/stories/980190962" to be === "http://www.example.com/stories/980190963".
它似乎将故事网址偏移了一个
这是失败的具体测试:
assert_redirected_to story_url(@story)
我尝试更改测试应该说的内容,但这会导致错误或失败。
这是失败的测试:
test "adds a story" do
assert_difference "Story.count" do
post stories_path, params: {
story: {
name: 'test story',
link: 'http://www.test.com/'
}
}
end
assert_redirected_to story_url(@story)
assert_not_nil flash[:notice]
end
这是控制器操作
def create
@story = Story.new(story_params)
respond_to do |format|
if @story.save
format.html { redirect_to story_url(@story), notice: "Story was successfully created." }
format.json { render :show, status: :created, location: @story }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @story.errors, status: :unprocessable_entity }
end
end
end
正如您在评论中已经提到的,使用时
setup do
@story = stories(:one)
end
然后由装置创建的
one
故事被分配给 @story
,而不是刚刚在测试期间创建的故事。
相反,我建议将您的测试更改为:
test "adds a story" do
assert_difference "Story.count" do
post stories_path,
params: { story: { name: 'test story', link: 'http://www.test.com/' } }
end
assert_redirected_to story_url(Story.last)
assert_equal "Story was successfully created.", flash[:notice]
end